2013-05-31 13 views
0

我有下面的代码,其正在努力从一个字符串过滤出粗话,并与askerisks取代他们,但是我想数的askerisks等于粗俗单词中的字母数量。例如,如果“屁股”一词被审查,那么它将被三个askerisks取代。我如何修改此代码以实现此目的?谢谢。为星号代替粗话,并有星号的数量相匹配的粗话的字母数

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

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

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

那将会给你更多的麻烦比它的价值:考虑'我爱CL ***的iCal music' –

+0

没有你好它会留下古典音乐,因为如果在词的前后存在空格,它只会匹配单词。 –

+0

试试我的解决方案? – silkfire

回答

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); 
} 
+1

但是,这会赶上例如'古典音乐' –

+0

啊,因此,任何一方的空间。将更新我的答案 – dKen

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); 
} 
+0

但是,这会赶上,例如'古典音乐' –

+0

修正了正则表达式。 – silkfire