G
G
Gleb Starkov2013-02-11 14:52:43
PHP
Gleb Starkov, 2013-02-11 14:52:43

Replacing bad words in a message with asterisks

I am replacing bad words in messages with PHP.
I did not find a ready-made solution, I do something like this:

    public static function replaceFuckWords($message)
    {
        $pattern = '/ahole|ash0le|f u c k|bi.+ch/i'; // здесь сейчас не все слова, список будет большой
        return preg_replace($pattern, '*****', $message);
    }



That is, the regular expression finds such words and changes them to five asterisks. All OK.

But you need to replace it not with five stars (as it is now), but with the number corresponding to the found bad word.
For example, cipa should be replaced with **** (four asterisks), and fatass should be replaced with ****** (six asterisks) Does

anyone have a ready-made solution, or an idea how to implement it? I will be grateful, thanks.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
@
@antoo, 2013-02-11
@colonel

You can modify your code like this:

function replaceFuckWords($message)
{
    $pattern = '/(ahole|ash0le|f u c k|bi.+ch)/ie';
    return preg_replace($pattern, "str_repeat('*', strlen('$1'))", $message);
}

The essence of the e modifier (PREG_REPLACE_EVAL).

P
Pe4enie, 2013-02-11
@Pe4enie

The simplest search in Google - www.awsinternet.com/articles/2005/PHP_Bad_word_vulgar_word_filter.html

S
splitface, 2013-02-11
@splitface

Here Kohana has a method in the Text class for replacing matyukov .

A
Alexander Gorsky, 2013-02-11
@alcanoid

For example cipa, you need to replace with **** (four asterisks)
Part****tion .
Be careful with patterns! I remember once I flew out of the chat while trying to enter the word "turpentine". It is unlikely that your users will be delighted with such a turn of events.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question