TeddyKiller Posted June 13, 2010 Share Posted June 13, 2010 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 https://forums.phpfreaks.com/topic/204620-replace-bad-words-with-stars-problem/ Share on other sites More sharing options...
JasonLewis Posted June 13, 2010 Share Posted June 13, 2010 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 https://forums.phpfreaks.com/topic/204620-replace-bad-words-with-stars-problem/#findComment-1071435 Share on other sites More sharing options...
Daniel0 Posted June 13, 2010 Share Posted June 13, 2010 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 https://forums.phpfreaks.com/topic/204620-replace-bad-words-with-stars-problem/#findComment-1071438 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.