Reputation: 27
I need something like this
$keywords = array('google', 'yahoo', 'facebook');
$mystring = 'alice was going to the yahoo CEO and couldn't him her';
$pos = strpos($mystring, $keywords);
if ($pos === false) {
echo "The string '$keywords' was not found in the string '$mystring'";
}
Basically I need to search several terms in a string if find if any exists in the string.
I'm wondering if it would be possible to set the keywords /search to case insensitive
Upvotes: 0
Views: 610
Reputation: 173562
Just iterate over the keywords and stop when you find at least one:
$found = false;
foreach ($keywords as $keyword) {
if (stripos($mystring, $keyword) !== false) {
$found = true;
break;
}
}
if (!$found) {
echo sprintf("The keywords '%s' were not found in string '%s'\n",
join(',', $keywords),
$mystring
);
}
Alternatively, use regular expressions with an alternation:
$re = '/' . join('|', array_map(function($item) {
return preg_quote($item, '/');
}, $keywords)) . '/i';
if (!preg_match($re, $mystring)) {
echo "Not found\n";
}
Upvotes: 1