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

时间:2013-04-07 12:27:00

标签: php

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

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

$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)

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

7 个答案:

答案 0 :(得分:58)

为此,您需要Regular Expressionspreg_match功能。

类似的东西:

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

您的尝试不起作用的原因

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

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

答案 1 :(得分:23)

你做不到这样的事情:

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

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

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

答案 2 :(得分:10)

strpos会搜索您传递的确切字符串作为第二个参数。如果要检查多个单词,则必须使用不同的工具

正则表达式

if(preg_match("/\b(bad|naughty)\b/", $data)){
    echo "Found";
}

preg_match如果字符串中有匹配则返回1,否则返回0。

多个str_pos调用

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

爆炸

if (count(array_intersect(explode(' ', $data),array('bad','naugthy')))) {
    echo "Found";
}

对我来说,首选的解决方案应该是第一个。很明显,由于使用正则表达式可能效率不高,但它不会报告误报,例如,如果字符串包含单词 badmington

,它将不会触发回显

正则表达式可能会成为创建的负担,如果它有很多单词(尽管$regex = '/\b('.join('|', $badWords).')\b/';

,但你无法通过一行php解决这些问题

第二个是直接的,但无法区分 badmington

如果第三个字符串用空格分隔,则第三个字符串将字符串拆分,选项卡字符将破坏您的结果。

答案 3 :(得分:7)

if(preg_match('[bad|naughty]', $data) === true) { }

以上不太正确。

"如果模式与给定主题匹配,则preg_match()返回1,如果不匹配则返回0,如果发生错误则返回FALSE。"

所以应该只是:

if(preg_match('[bad|naughty]', $data)) { }

答案 4 :(得分:2)

你必须删除每个单词。现在您正在检查是否存在表明

的字符串
'bad || naughty'

不存在。

答案 5 :(得分:0)

substr_count()

我想添加一种使用substr_count()的方法(在所有其他答案之上):

if (substr_count($data, 'bad') || substr_count($data, 'naughty')){
    echo "Found";
}

substr_count()正在计算该字符串出现的次数,因此当它为0时,您知道找不到该字符串。 我想说这种方式比使用str_pos()(答案之一中提到的)更具可读性:

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

答案 6 :(得分:0)

使用待测词数组和array_reduce()函数的简单解决方案:

$words_in_data = array_reduce( array( 'bad', 'naughty' ), function ( $carry, $check ) use ( $data ) {
    return ! $carry ? false !== strpos( $data, $check ) : $carry;
} );

然后你可以简单地使用:

if( $words_in_data ){
    echo 'true';
}