检查一个字符串是否包含多个特定单词 [英] Check if a string contain multiple specific words

查看:264
本文介绍了检查一个字符串是否包含多个特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to check, if a string contain multiple specific words?

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

I can check single words using following code:

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

但是,我想添加更多单词来检查.像这样:

But, I want to add more words to check. Something like this:

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

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

(if any of these words is found then it should return true)

但是,以上代码无法正常工作.你知道我在做什么错吗?

But, above code does not work correctly. Any idea, what I'm doing wrong?

推荐答案

为此,您将需要正则表达式 preg_match 功能.

For this, you will need Regular Expressions and the preg_match function.

类似的东西:

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

您的尝试失败的原因

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

Regular Expressions are parsed by the PHP regex engine. The problem with your syntax is that you used the || operator. This is not a regex operator, so it is counted as part of the string.

正如上面正确指出的,如果它被视为您要匹配的字符串的一部分:'bad || naughty'作为字符串,而不是表达式!

As correctly stated above, if it's counted as part of the string you're looking to match: 'bad || naughty' as a string, rather than an expression!

这篇关于检查一个字符串是否包含多个特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆