In many object-oriented languages, you often want to check for the presence of a substring in a string. PHP does not contain a .contains() method which you can use, but you can create your own using the strpos() function quite easily:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Checks to see of a string contains a particular substring * @param $substring the substring to match * @param $string the string to search * @return true if $substring is found in $string, false otherwise */ function contains($substring, $string) { $pos = strpos($string, $substring); if($pos === false) { // string needle NOT found in haystack return false; } else { // string needle found in haystack return true; } } |
Although this function is not very complex, it can simplify your code by reducing statements like if (strpos($str, $substr) == -1) to simply if (contains($str, $substr).




