正则表达式与单词边界匹配太松散


Regex matching too loosely with word boundaries

我有以下代码,我尝试使用单词边界精确匹配特定单词,将它们替换为"审查",然后重建文本,但由于某种原因正则表达式捕获尾部斜杠。为了清楚起见,我已经简化到以下测试用例

<?php
$words = array('bad' => "censored");
$text = "bad bading testbadtest badder";
$newtext = "";
foreach( preg_split( "/('['/?(?:acronym|background|'*)(?:=.+?)?']|(^|'W)bad('W|$))/i", $text, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY ) as $section )
{
    if ( isset( $words[ $section ] )  )
    {
        $newtext .= $words[ $section ];
    }
    else
    {
        $newtext .= $section ;
    }
}
var_dump($newtext);

退出;

在这个例子中,我希望匹配"坏",但不匹配坏测试坏测试或坏。问题是"坏"(注意尾随空格)正在匹配,它不作为$words数组中的键存在。

有人可以解释一下我可能出错的地方吗?

提前致谢

我想

我会采取不同的方法,因为我不确定你为什么要使用preg_split()并在正则表达式中硬编码你的审查单词。

只需构建一系列要替换的模式及其替换并使用preg_replace()

// note no space in words or their replacements
$word_replacement_map = array(
    'bad' => 'b*d',
    'alsobad' => 'a*****d'
);
$bad_words = array_keys($word_replacement_map);
$patterns = array_map(function($item) {
    return '/'b' . preg_quote($item) . ''b/u';
}, $bad_words);
$replacements = array_values($replacement_map);
$input_string = 'the string with bad and alsobad words';
$cleaned_string = preg_replace($patterns, $replacements, $input_string);
var_dump($cleaned_string); // the string with b*d and a*****d words

请注意,如果您不需要特定于单词的替换,则可以将其简化为:

// note no space in words
$bad_words = array(
    'bad',
    'alsobad'
);
$replacement = 'censored';
$patterns = array_map(function($item) {
    return '/'b' . preg_quote($item) . ''b/u';
}, $bad_words);
$input_string = 'the string with bad and alsobad words';
$cleaned_string = preg_replace($patterns, $replacement, $input_string);
var_dump($cleaned_string); // the string with censored and censored words

请注意,我在正则表达式模式中使用了单词边界,这通常应该满足您的需求。