使用正则表达式替换单词

Replace words using regular expression

我有一个网站,在发布之前需要过滤用户内容(评论等)。目前我有一个系统,可以根据单词列表扫描发布的内容,然后用星号替换这些单词。

这对单个单词来说效果很好,但我现在正在寻找替换单词序列的方法,但我有点迷路了。

对于示例,我们将使用 PayPal。目前我的正则表达式可以很好地找到并替换它,但是如果我想搜索并替换 'Pay Pal' 它不会。这是我到目前为止适用于单个单词的替换代码:

$word = $words->word;
$length = strlen($word);

$replacement = str_repeat('*', $length);

$newContent = preg_replace('/\b'.$word.'\b/i', $replacement, $content);

所以我需要它用'* *'替换'pay pal'。

理想情况下,space 将是一个通配符,用于选择诸如 'pay_pal' 之类的东西,但这真是太好了。

我玩过,没用。

澄清一下 - 我如何修改它以替换两个词以及一个词?

$newContent = preg_replace('/\b'.$word.'\b/i', $replacement, $content);

太糟糕了。真的,真的很糟糕。就像坐直升飞机去离家20米外的购物一样。

对于完全固定的文本块,请使用 str_replace()

$newContent = str_replace($word, $replacement, $content);
// If you want it to be surrounded with spaces use the one below:
$newContent = str_replace(" $word ", $replacement, $content);

对于像"PayPal"这样更复杂的,我建议你以"Pay*Pal"的形式存储它,或者其他方式。示例:

$badWord = 'Pay*Pal';
$pattern = '~\b'.str_replace('*','.?',$badWord).'\b~Ui'; 
// dont use 'i' flag if you want it case-sensitive
$newContent = preg_replace($pattern, $replacement, $content);