Using strpos in PHP requires attention to the === operator

  • 2020-03-31 20:56:47
  • OfStack


<?php 
 
function strexists($haystack, $needle) { 
return !(strpos($haystack, $needle) === FALSE);//Notice the "===" here.
} 
 
$mystring = 'abc'; 
$findme = 'a'; 
$pos = strpos($mystring, $findme); 

// Note our use of ===. Simply == would not work as expected 
// because the position of 'a' was the 0th (first) character. 
//Simply using the "==" sign will not work, you need to use the "===" sign, because the first time a appears, the position is 0
if ($pos === false) { 
echo "The string '$findme' was not found in the string '$mystring'"; 
} else { 
echo "The string '$findme' was found in the string '$mystring'"; 
echo " and exists at position $pos"; 
} 

// We can search for the character, ignoring anything before the offset 
//The offset can be specified using the parameter offset when searching for characters
$newstring = 'abcdef abcdef'; 
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0 
?>

Related articles: