How do you use the strpos
for an array of needles when searching a string? For example:
$find_letters = array('a', 'c', 'd'); $string = 'abcdefg'; if(strpos($string, $find_letters) !== false) { echo 'All the letters are found in the string!'; }
Because when using this, it wouldn't work, it would be good if there was something like this
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.
Definition and Usage. The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.
@Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351
function strposa($haystack, $needles=array(), $offset=0) { $chr = array(); foreach($needles as $needle) { $res = strpos($haystack, $needle, $offset); if ($res !== false) $chr[$needle] = $res; } if(empty($chr)) return false; return min($chr); }
How to use:
$string = 'Whis string contains word "cheese" and "tea".'; $array = array('burger', 'melon', 'cheese', 'milk'); if (strposa($string, $array, 1)) { echo 'true'; } else { echo 'false'; }
will return true
, because of array
"cheese"
.
Update: Improved code with stop when the first of the needles is found:
function strposa(string $haystack, array $needles, int $offset = 0): bool { foreach($needles as $needle) { if(strpos($haystack, $query, $offset) !== false) { return true; // stop on first true result } } return false; } $string = 'This string contains word "cheese" and "tea".'; $array = ['burger', 'melon', 'cheese', 'milk']; var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With