gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:59:51 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

为此,您需要 Regular Expressionspreg_match功能。

类似:

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

你的尝试失败的原因

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

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

关于php - 检查字符串是否包含多个特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com