PHP Preg_匹配字符串中的每个单词,以查找与包含禁止单词的数组中所有项目的匹配项
我有一张禁词清单。我必须检查那些被禁止的单词是否在给定的字符串中。我当前的代码部分工作正常 仅当且仅当满足以下条件时,匹配才应为PHP Preg_匹配字符串中的每个单词,以查找与包含禁止单词的数组中所有项目的匹配项,php,preg-match,implode,Php,Preg Match,Implode,我有一张禁词清单。我必须检查那些被禁止的单词是否在给定的字符串中。我当前的代码部分工作正常 仅当且仅当满足以下条件时,匹配才应为true: 字符串中的任何单词都与任何禁止的单词完全匹配,例如:池是冷的 字符串中的任何单词都以任何禁止的单词开头,例如:池侧为黄色 匹配应为false否则,这包括两种情况,这两种情况目前都不正常: 如果字符串中的任何单词以任何禁止的单词结尾,例如:汽车泳池车道关闭 如果字符串中的任何单词包含任何禁止的单词,例如:print spooler不起作用 当前代码: $for
true
:
false
否则,这包括两种情况,这两种情况目前都不正常:
$forbidden = array('pool', 'cat', 'rain');
// example: no matching words at all
$string = 'hello and goodbye'; //should be FALSE - working fine
// example: pool
$string = 'the pool is cold'; //should be TRUE - working fine
$string = 'the poolside is yellow'; //should be TRUE - working fine
$string = 'the carpool lane is closed'; //should be FALSE - currently failing
$string = 'the print spooler is not working'; //should be FALSE - currently failing
// example: cat
$string = 'the cats are wasting my time'; //should be TRUE - working fine
$string = 'the cat is wasting my time'; //should be TRUE - working fine
$string = 'joe is using the bobcat right now'; //should be FALSE - currently failing
// match finder
if(preg_match('('.implode('|', $forbidden).')', $string)) {
echo 'match!';
} else {
echo 'no match...';
}
相关优化注意事项:官方的
$forbidden
单词数组有350多个项目,平均给定的$string
大约有25个单词。因此,如果解决方案在找到第一个匹配项时立即停止preg\u match
过程,那就太好了。关键是对单词边界使用\b
断言:
所以你想要的就是如果(preg_match('/\b(?:'.inplade('/\b(?))/',$string)){
?。请参见“/\b(“.inplade('.\124;“,$inplated”)”)/i“
-\b
确保匹配只从一个单词开始,而不是从中间或结尾开始。它也适用于整个单词,因为它们也是“开始”的与匹配。你的答案非常有效。遗憾的是,我的问题被标记为重复。我知道这不是原始问题,但我也在尝试匹配póol(无需将póol、poól或pól变体添加到禁止词数组中)。我认为在preg_match
regex中添加u
标志就足够了,但事实并非如此。对此有什么想法吗?我能提供的最佳解决方案是创建一个函数antispoof(string$probidden):string
,用$probidden
替换$probidden
中的任何“o”\u00b4?\u0300?
(包括西里尔字母和希腊文字母,但应该更长),对于任何信件也是如此。但是,PHP可以提供现成的反欺骗解决方案。我感谢您的帮助