PHP从数组中搜索另一个字符串


php search string in another string from array

我需要这样的东西

$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'";
} 

基本上我需要在字符串中搜索几个术语,如果找到是否存在于字符串中。

我想知道是否可以将关键字/搜索设置为不区分大小写

只要遍历关键字,找到至少一个就停止:

$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";
}