替换星号粗鲁的单词,星号的数量与粗鲁的单词中的字母数相匹配

时间:2013-05-31 08:31:35

标签: php preg-replace str-replace

我有以下代码正在努力从字符串中过滤掉粗鲁的单词并用askerisks替换它们但是我希望askerisks的数量等于粗鲁单词中的字母数量。例如,如果“屁股”这个词被审查,那么它将被三个问题所取代。如何修改此代码才能实现此目的?感谢。

$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc

foreach ($naughtyWords as &$word) {
    $word = ' '.$word.' ';
}

$string = str_replace($naughtyWords, " **** ", ' '.$string.' ');

2 个答案:

答案 0 :(得分:2)

试试这个:

$naughty_words = array('ahole', 'anus', 'ash0le', 'ash0les', 'asholes', 'ass');
$string = 'classical music ass dirty ass. molass';

foreach ($naughty_words as $naughty_word) {
    $string = preg_replace_callback('#\b' . $naughty_word . '\b#i', function($naughty_word) {return str_repeat('*', strlen($naughty_word[0]));}, $string);
}

答案 1 :(得分:0)

尝试:

$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc

foreach ($naughtyWords as $word) {
    $replacement = str_repeat('*', strlen($word));
    $string = str_replace(' '.$word.' ', $replacement, $string);
}