So, today I wrote the dirtiest function I have ever written in PHP. I typed more profanity at once than I think I ever have in the past. As part of a new AJAX (Asynchronous Javascript And XML) live search query displayer I wrote for our Google Mini, I had to do some filtering to make sure naughty phrases wouldn’t show up. This is a pretty straightforward script you could incorporate into different applications, like a shoutbox, or comment form.
Alternatively, you could swap in preg_replace() or eregi_replace() instead of preg_match() and censor phrases that way. In this example, I use preg_match() just to test the query, and if the filter matched, I excluded the query from display entirely. I have this set to match anything that occurs in a query, so if the word “butt” was a filter term, it would catch “butts,” “butthole,” and “buttmunch.” That saved a lot of extra typing and filtering. Yes, it increases the likelihood of a false positive, but in this case we weren’t too concerned about an overly aggressive filter.
If the filter makes a match, it returns a boolean value of true. From there, do as you will. You could build in your own handler code as well (especially if you just wanted to censor individual words).
If you have a better idea or refinement, comment below and I can tweak this appropriately.
Posting tweet...