用星号替换不礼貌的单词,星号的数量与不礼貌单词中的字母数量相匹配


Replace rude words for asterisks and have the number of asterisks match the number of letters in the rude words

我有以下代码,它正在从字符串中过滤出粗鲁的单词,并将它们替换为askerisks,但是我希望askerisks的数量等于粗鲁单词中的字母数量。例如,如果"ass"这个词被删除,那么它将被三个askerisk所取代。我如何修改这段代码来实现这一点?谢谢。

$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc
foreach ($naughtyWords as &$word) {
    $word = ' '.$word.' ';
}
$string = str_replace($naughtyWords, " **** ", ' '.$string.' ');

试试这个:

$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);
}

尝试:

$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc
foreach ($naughtyWords as $word) {
    $replacement = str_repeat('*', strlen($word));
    $string = str_replace(' '.$word.' ', $replacement, $string);
}