问题
I have the following code which is working to filter out rude words from a string and replace them with askerisks however I would like the number of askerisks to equal the number of letters in the rude word. For example if the word 'ass' was censored then it would be replaced with three askerisks. How do I modify this code to achieve this? Thanks.
$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc
foreach ($naughtyWords as &$word) {
$word = ' '.$word.' ';
}
$string = str_replace($naughtyWords, " **** ", ' '.$string.' ');
回答1:
Try this:
$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);
}
回答2:
Try:
$naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc
foreach ($naughtyWords as $word) {
$replacement = str_repeat('*', strlen($word));
$string = str_replace(' '.$word.' ', $replacement, $string);
}
来源:https://stackoverflow.com/questions/16853069/replace-rude-words-for-asterisks-and-have-the-number-of-asterisks-match-the-numb