Word replacements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Word replacements

Post 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?
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Word replacements

Post 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);
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Re: Word replacements

Post 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.
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Word replacements

Post 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'
Post Reply