这是另一种解决方案,匹配单词并用 str 的 * len 替换。这不会匹配像 Scunthorpe 这样的单词,因为它使用单词边界,您还可以添加第三个参数来显示单词的第一个字母,这样您就知道说了什么单词而不看它。
<?php
$badwords = array('*c word', '*f word','badword','stackoverflow');
function swear_filter($str,$badwords,$reveal=null) {
//Alternatively load from file
//$words = join("|", array_filter(array_map('preg_quote',array_map('trim', file('badwords.txt')))));
$words = join("|", array_filter(array_map('preg_quote',array_map('trim', $badwords))));
if($reveal !=null && is_numeric($reveal)){
return preg_replace("/\b($words)\b/uie", '"".substr("$1",0,'.$reveal.').str_repeat("*",strlen("$1")-'.$reveal.').""', $str);
}else{
return preg_replace("/\b($words)\b/uie", '"".str_repeat("*",strlen("$1")).""', $str);
}
}
$str="There was a naughty Peacock from Scunthorpe and it said a badword, on stackoverflow";
//There was a naughty Peacock from Scunthorpe and it said a b******, on s************
echo swear_filter($str,$badwords,1);
//There was a naughty Peacock from Scunthorpe and it said a *******, on *************
echo swear_filter($str,$badwords);
?>