PHP Preg_match 要查找的字符串中的每个单词都与包含禁止单词的数组中的所有项目匹配

PHP Preg_match each word in a string to find matches with all the items in an array that contains forbidden words

我有一个禁用词列表。我必须检查这些禁用词之一是否在给定字符串内。我当前的代码工作正常部分

一场比赛应该是 true 只有并且只有在:

  1. 字符串中的任何单词与任何禁止的单词完全匹配,例如:pool is cold.
  2. 字符串中的任何单词以任何禁止的单词开头,例如:poolside is yellow.

匹配应该是 false 否则,这包括目前不能正常工作的这两种情况:

  1. 如果字符串中的任何单词以任何禁止单词结尾,例如:汽车pool lane is closed.
  2. 如果字符串中的任何单词包含任何禁止的单词,例如:打印 spooler 不工作。

当前代码:

$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_match 进程,那就太好了。

关键是对word-boundary使用\b断言:

<?php
$forbidden = ['pool', 'cat', 'rain'];

// Examples
$examples = [
    // pool:
    'the pool is cold', //should be TRUE - working fine
    'the poolside is yellow', //should be TRUE - working fine
    'the carpool lane is closed', //should be FALSE - currently failing
    'the print spooler is not working', //should be FALSE - currently failing

    // cat:
    'the cats are wasting my time', //should be TRUE - working fine
    'the cat is wasting my time', //should be TRUE - working fine
    'joe is using the bobcat right now', //should be FALSE - currently failing
];

$pattern = '/\b(' . implode ('|', $forbidden) . ')/i';

foreach ($examples as $example) {
    echo ((preg_match ($pattern, $example) ? 'TRUE' : 'FALSE') . ': ' . $example . "\n");
}

http://sandbox.onlinephpfunctions.com/code/f424e6c78d3b13905486f646667c8bc9d48eda3a