Use php to check a string contains substring there maybe many ways, the strpos maybe the most used way, but it’s strange, it not work for me why? That’s what i want to say: the thing you need take care while use strpos .
what’s strpos
Check the php Manual: " strpos — Find position of first occurrence of a string "
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] ) |
and for the return value:
"Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE. "
Here is how i use this:
$str = 'google.com'; $find= 'gle.'; if(strpos($str, $find)) { echo "find "; } else { echo "not find"; } |
Run it,it seems works correctly.Do you find the problem? For this sample,It work but let’s try this one:
$str = 'google.com'; $find= 'google.'; if(strpos($str, $find)) { echo "find "; } else { echo "not find"; } |
It’s show "not find", why? the strpos return 0, not 1 . so even the substring found , it’s still show "not find"
the right way for strpos
Since we know strpos will give a numeric value if found else it is null or false,so let’s see the right way:
$str = 'google.com'; $find= 'google.'; if(is_numeric(strpos($str, $find))) { echo "find "; } else { echo "not find"; } |
Or
$str = 'google.com'; $find= 'google.'; $isfound=strpos($str, $find); if($isfound!== false) { echo "find "; } else { echo "not find"; } |
So you know more about strpos now,Happy reading!