在字符串中使用空格匹配单词列表


Match a list of words in a string with space inbetween characters

假设我有一个看起来像这样的字符串:

快把你的裤子给我!

和禁用词列表:

钱包,香蕉,土豆

我该如何编写正则表达式来捕获这些单词呢?即使字符之间有空格

欢呼。

下面的代码将完成以下工作:

foreach($banned as $word) {
    $chars = str_split($word);
    $pattern = implode(' ?', $chars);
    $check = preg_match('/'.$pattern.'/i', $text);
}

$ prohibited——

$text是要验证的文本

和$复选标记,如果给定的禁用词被发现,并根据您想要实现的逻辑,以适当的方式使用该变量

捕捉任何单词的简单方法(不含空格):

function censorship($bannedwords, $sentence) {
    foreach($bannedwords as $word) $sentence = str_replace($word, '****', $sentence);
    return $sentence;
}
$bannedwords = ['banana', 'potato'];
echo censorship($bannedwords, 'Every banana is a potato');
// Output : Every **** is a ****