Page 1 of 1

Word replacements

Posted: Wed Aug 08, 2012 9:08 pm
by Pazuzu156
I have a bit of a issue. I'm building a chat app for my website, and users have the option to enable profanity filtering. However, if say the user uses ass, it replaces it with ***

The issue is when it replaces that, say they use the word bassist, it replaces that with b***ist. I'm using str_replace() for the content. How do I prevent this from happening?

Re: Word replacements

Posted: Thu Aug 09, 2012 12:07 am
by requinix
Use regular expressions. A simple version would be

Code: Select all

$censored = preg_replace_callback('/\b(foo|bar|ass)\b/i', function($matches) { return str_repeat("*", strlen($matches[1])); }, $uncensored);

Re: Word replacements

Posted: Fri Aug 10, 2012 1:22 am
by Pazuzu156
That might work. How exactly would I go about using something like that from the words that are within an array? I'm thinking in_array() or looping it. But I don't know how to go about doing that.

Re: Word replacements

Posted: Fri Aug 10, 2012 2:06 am
by requinix
Make everything in the array be either:
a) a valid regular expression (just a subexpression, not the full thing like with delimiters) - this allows you to have more flexible "words"

Code: Select all

$array = array("foo", "bar", "pi\|pe");
or b) a straight text string, then preg_quote() it - this only allows exact matches

Code: Select all

$array = array("foo", "bar", "pi|pe");
$array = array_map("preg_quote", $array);
Then implode() it into a pipe-separated list and stick it in the regex.

Code: Select all

'/\b(' . implode('|', $array) . ')\b/i'