0

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

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

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

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

2 回答 2

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);
}
于 2013-05-31T08:38:10.707 回答
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);
}
于 2013-05-31T08:36:57.967 回答