1

I'm writing a very basic commenting system and want to implement a simple, efficient bad words filter.

I'm aware of the problems associated with bad word filters and realize it's basically impossible to write one that keeps misspellings and innuendo out, but I'm just wanting to write a very simple one that keeps correct spellings of vulgar words from being displayed.

I found a bad words list of about 400 words and put it into preg_replace() with the pattern being:

/(these|are|bad|words|like|ass)/

The problem is that it replaces any occurrence of the characters in the pattern, even if they are in the middle of a word. So, for example, assist will be replaced with ist.

Second question: instead of replacing the bad words with an empty string, or with a fixed-width string such as ****, is there a way to replace it with a string of asterisks with the same length of the replaced word?

1

3 Answers 3

6
preg_replace_callback(
    '/\b(these|are|bad|words|like|ass)\b/',
    function (array $match) { return str_repeat('*', strlen($match[1])); },
    $comment
)

\b is a word boundary and will probably suffice for most cases; though it probably won't be perfect for all cases.

3
  • Very slick, thank you! As a somewhat unrelated question, do you think using this with a long list of words (a few hundred) would be inefficient, or do you think it would be OK?
    – Nate
    May 14, 2014 at 13:15
  • Using a regular expression like this is probably going to be as efficient as it gets. Benchmark it if you're really concerned.
    – deceze
    May 14, 2014 at 13:30
  • 1
    Remember to use the case-insensitive flag `'/.../i' for obvious reasons. Regexps are going to be the fastest way to do this in PHP, especially as the PHP runtime system compiles and caches patterns internally so the expensive bit (compiling) the regexp will only be done once. This also means that you can improve the maintainability of your code by keeping the work list as an array and building the pattern with a few lines of PHP on the first invocation.
    – TerryE
    May 23, 2014 at 16:27
3

You could use word boundaries:

/\b(these|are|bad|words|like|ass)\b/
1

First off, one thing you want is word_boundary characters \b they are zero width and match the boundary of a word so make your regex:

/\b(these|are|bad|words|like|ass)\b/

secondly, to replace the string with another one of equal length just use a function that operates on the match.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.