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?
Word replacements
Moderator: General Moderators
Word replacements
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
Re: Word replacements
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
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.
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
Re: Word replacements
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"
or b) a straight text string, then preg_quote() it - this only allows exact matches
Then implode() it into a pipe-separated list and stick it in the regex.
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");Code: Select all
$array = array("foo", "bar", "pi|pe");
$array = array_map("preg_quote", $array);Code: Select all
'/\b(' . implode('|', $array) . ')\b/i'