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

我是研究僧i 提交于 2019-12-25 05:27:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!