Php 将粗体字替换为星号,并使星号的数量与粗体字中的字母数量相匹配

Php 将粗体字替换为星号,并使星号的数量与粗体字中的字母数量相匹配,php,preg-replace,str-replace,Php,Preg Replace,Str Replace,我有下面的代码,用于从字符串中过滤出粗鲁的单词,并用askerisk替换它们,但是我希望askerisk的数量等于粗鲁单词中的字母数量。例如,如果“ass”一词被审查,那么它将被三个askerisk替换。如何修改此代码以实现此目的?谢谢 $naughtyWords = array("ahole","anus","ash0le","ash0les","asholes","ass"); //etc foreach ($naughtyWords as &$word) { $word

我有下面的代码,用于从字符串中过滤出粗鲁的单词,并用askerisk替换它们,但是我希望askerisk的数量等于粗鲁单词中的字母数量。例如,如果“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);
}

这将给你带来更多的麻烦:考虑<代码>我喜欢Cl****ic音乐 Hello No,它只会留下古典音乐,因为它只匹配单词,如果单词前后存在一个空间。但是这将捕获例如“代码>古典音乐< /代码>,但这将捕获例如代码<经典音乐< /代码>固定的规则。表情。
$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);
}