0

我需要这样的东西

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

基本上,如果查找字符串中是否存在任何项,我需要在字符串中搜索多个术语。

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

4

1 回答 1

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";
}
于 2013-04-02T03:45:16.140 回答