php – 检查字符串是否包含任何单词

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 检查字符串是否包含任何单词脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要检查一个字符串是否包含任何一个禁止的单词.我的要求是:

>不区分大小写,这就是我使用strIPOs()的原因
>单词应该用空格分隔,例如,如果禁止的单词是“扑克”,“扑克游戏”或“游戏扑克比赛”应该被禁止的字符串和“trainpokering great”应该在良好的字符串下.

我尝试过类似下面的内容

$string  = "poker park is great";

if (stripos($string,'poker||casino') === false) 
{

echo "banned words found";
}
else

{
echo $string;
}

解决方法

您可以使用数组并加入它

$arr = array('poker','casino','some','other','word','regex+++*much/escaping()');
$string = 'cool guy';

for($i = 0,$l = count($arr); $i < $l; $i++) {
    $arr[$i] = PReg_quote($arr[$i],'/');   // Automagically escaPE regex tokens (think about quantifiers +*,[],() delimITers etc...)
}
//print_r($arr); // Check the results after escaping

if(preg_match('/\b(?:' . join('|',$arr). ')\b/i',$string)) { // Now we don't need to fear 
    echo 'banned words found';
} else {
    echo $string;
}

它使用单词边界并连接数组.

脚本宝典总结

以上是脚本宝典为你收集整理的php – 检查字符串是否包含任何单词全部内容,希望文章能够帮你解决php – 检查字符串是否包含任何单词所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。