检查字符串是否包含多个特定单词

php
2022-08-30 10:41:02

如何检查字符串是否包含多个特定单词?

我可以使用以下代码检查单个单词:

$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad') !== false) {
    echo 'true';
}

但是,我想添加更多单词进行检查。像这样:

$data = "text text text text text text text bad text text naughty";
if (strpos($data, 'bad || naughty') !== false) {
    echo 'true';
}

(如果找到这些单词中的任何一个,那么它应该返回true)

但是,上面的代码无法正常工作。任何想法,我做错了什么?


答案 1

为此,您将需要正则表达式preg_match函数。

像这样:

if(preg_match('(bad|naughty)', $data) === 1) { } 

您的尝试不起作用的原因

正则表达式由 PHP 正则表达式引擎解析。语法的问题在于使用了运算符。这不是正则表达式运算符,因此它被计为字符串的一部分。||

如上所述,如果它被算作您要匹配的字符串的一部分:作为字符串,而不是表达式!'bad || naughty'


答案 2

你不能做这样的事情:

if (strpos($data, 'bad || naughty') !== false) {

相反,您可以使用正则表达式:

if(preg_match("/(bad|naughty|other)/i", $data)){
 //one of these string found
}

推荐