Jump to content

Replace bad words with stars problem


TeddyKiller

Recommended Posts

The problem with the code below, is that it doesn't match the bad words. So I removed the if statement, and kept the preg_replace, and.. it erases the text. I'm not sure what I did wrong...

 

$badwords = array(NAUGHTY WORDS HERE);
                 
$sensors = array(STARS HERE);
                 
if(preg_match($badwords, $message)) {
       $message = preg_replace($badwords, $sensors, $message);
}

 

I have $message = preg_replace($patterns, $replacements, $message); above that.. which what that does, is allows smilies in the text. So $patterns = : ), and replaced it with an image. That works fine.. but the bit for bad words doesn't..

 

Any ideas? Cheers

 

---------------------------

Edit

Str_replace did the trick, but why wouldn't it work with preg?

Link to comment
Share on other sites

Because preg_replace() is for regular expressions. Depends how you had set out your badwords array though.

 

If you set it out like this:

 

$badwords = array("word1","word2","word3");

 

It wouldn't have worked, however like this it would have:

 

$badwords = array("/word1/","/word2/","/word3/");

Link to comment
Share on other sites

You'll have to be careful with that approach. For instance, you risk censoring "grass" to "gr***" when you censor "ass".

 

You can "fix" that like this:

 

$badwords = array('bad1', 'bad2', 'bad3', 'ass');

$text = 'This is a test. Ass. Grass. bad1.';

function filterBadwords($text, array $badwords, $replaceChar = '*') {
    return preg_replace_callback(
        array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords),
        function($match) use ($replaceChar) { return str_repeat($replaceChar, strlen($match[0])); },
        $text
    );
}

echo filterBadwords($text, $badwords);

 

Output is:

This is a test. ***. Grass. ****.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.