用星号替换粗鲁的单词,并使星号的数量与粗鲁单词中的字母数量相匹配 [英] Replace rude words for asterisks and have the number of asterisks match the number of letters in the rude words

查看:37
本文介绍了用星号替换粗鲁的单词,并使星号的数量与粗鲁单词中的字母数量相匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.' ');

推荐答案

试试这个:

$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);
}

这篇关于用星号替换粗鲁的单词,并使星号的数量与粗鲁单词中的字母数量相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆