Sorry, I couldn't find the answer to this, but I'm using str_contains
to find matches of a str within another str.
str_contains($haystack, $needle);
However, is there a way to have multiple needles or do I need to use this function several times?
CodePudding user response:
There is no built-in function to do this, but you can make your own
function str_containsa(string $haystack, array $needles){
foreach ($needles as $needle){
if (str_contains($haystack, $needle)){
return true;
}
}
return false;
}
usage
str_containsa('the quick brown fox jumped over the lazy dog', ['fox', 'cow', 'goat']);
//returns true as string contains fox
CodePudding user response:
also you can use regex and preg_match_all:
- join needles into pattern string like
(\bneedle1\b)|(\bneedle2\b)
etc - make regex pattern case insensitive
i
and search multilinem
function stringHasWords(string $string, array $needles)
{
$nPattern = join('|', array_map(function ($needle) {
// note \b token
return "(\b$needle\b)";
}, $needles));
// m - multiline, i - case insensitive
$pattern = "/$nPattern/mi";
// returns count of matches or false on error
$count = preg_match_all($pattern, $string, $matches);
return $count && $count > 0;
}
note that \b
token makes regex search only exact words, no match for o
in string fox