[英]php search string in another string from array
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 我想知道是否可以将关键字/ search设置为不区分大小写
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.