strstr()可以用来在一个句子中查找两个单独的关键字吗


can strstr() be used to look for 2 separate key words within a sentence?

strstr()可以用来在一个句子中查找两个单独的关键字吗?

例如:

$sentence = 'the quick brown fox';
if (strstr($sentence, 'brown') && strstr($sentence, 'fox')) {
   echo 'YES';
} else {
   echo 'NO';
}

这取决于您使用它的目的。从外观上看,您应该使用strpos,而不是strstr

是的,它可以。。。您所拥有的脚本将返回YES。。总是因为strstr用于查找字符串的第一次出现及其工作,而与其他声明无关。。能够在两个不同的首次出现实例中找到CCD_ 5和CCD_

的工作方式

strstr($sentence, 'brown') // Returns 'brown fox' 
strstr($sentence, 'fox') // Returns 'fox' 

两个结果都是有效的字符串

如果你尝试

var_dump(strstr($sentence, 'fish')); // Returns false 

现在,这不是一种有效的字符串检查方法,但它有自己的使用

文件:http://php.net/manual/en/function.strstr.php

编辑1

$sentence = 'the quick brown fox';
$keywords = array (
        'brown',
        'fox' 
);
echo "<pre>";

preg_matchhttp://php.net/manual/en/function.preg-match.php

示例

$regex = '/(' . implode ( '|', $keywords ) . ')/i';
if (preg_match ( $regex, $sentence )) // Seach brown or fox
{
    echo "preg_match brown or fox" . PHP_EOL;
}

所有这些都将根据您的用例工作

strpos()-查找子串在跨区中第一次出现的位置

stripos()-查找字符串中第一个不区分大小写的子字符串的位置

strrpos()-查找字符串中子字符串最后一次出现的位置

strrchr()-查找字符串中最后一个出现的字符

示例

if (strpos ( $sentence, $keywords [0] ) || strpos ( $sentence, $keywords [1] )) {
    echo "strpos brown OR fox " . PHP_EOL;
}
if (strripos ( $sentence, $keywords [0] ) && strpos ( $sentence, $keywords [1] )) {
    echo "strpos brown AND fox " . PHP_EOL;
}

我希望这能帮助