我需要这样的东西
$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'";
}
基本上我需要在字符串中搜索几个术语,如果查找字符串中是否存在。
我想知道是否可以将关键字/搜索设置为不区分大小写
答案 0 :(得分:1)
只需迭代关键字并在找到至少一个时停止:
$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
);
}
或者,使用带有替换的正则表达式:
$re = '/' . join('|', array_map(function($item) {
return preg_quote($item, '/');
}, $keywords)) . '/i';
if (!preg_match($re, $mystring)) {
echo "Not found\n";
}