Web Development & WordPress

Mastering PHP String Search: The Differences Between strpos, stripos, and strripos Explained

  • stripos searches for the first occurrence of a substring in a string, ignoring case.
  • strripos searches for the last occurrence of a substring in a string, ignoring case.

CODE:

<?php
$string = "This is a test by Tom. He is a good boy. This is another test";
echo "Main sentence is:<br>";
echo $string;
echo '<br>Search the word "test" using strpos() <br>';
echo strpos($string, "test");

echo '<br>Search the word "Test" using strpos() <br>';
echo strpos($string, "Test");
if(strpos($string, "Test")){
    echo "Word Found";
}else{
    echo "Word not found--as strpos() is case sensitive";
}
echo '<br>Search the word "Test" using stripos()-- case sensitive <br>';
echo stripos($string, "Test");

echo '<br>Search the word "This" using stripos()-- case sensitive <br>';
 echo stripos($string, "This");
echo "<br>";
if(stripos($string, "This") !== false ){
    echo " Word  is found";
}else{
    echo "Word not found";
}
echo '<br>Search the word "This" using strripos()-- case sensitive. <br>';
 echo strripos($string, "This");

echo "<br>";
echo "Another Test<br>";

 $text = "This is a test. This is only a test.";
echo $text;
echo "<br>";
 $substring = "test";

$firstPos = stripos($text, $substring); 
$lastPos = strripos($text, $substring);  

echo "First occurrence of test: " . $firstPos . "\n";  
echo "Last occurrence of  test: " . $lastPos . "\n";    
?>

OUTPUT:

Main sentence is:
This is a test by Tom. He is a good boy. This is another test
Search the word "test" using strpos()
10
Search the word "Test" using strpos()
Word not found--as strpos() is case sensitive
Search the word "Test" using stripos()-- case sensitive
10
Search the word "This" using stripos()-- case sensitive
0
Word is found
Search the word "This" using strripos()-- case sensitive.
41
Another Test
This is a test. This is only a test.
First occurrence of test: 10 Last occurrence of test: 31

Leave a comment