Jordie Jordie - 1 year ago 65
PHP Question

How do I replace bad words with php?

I have some text i need to filter out a list of bad words in like:

$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',

I can loop through these and replace one at a time but that is slow right? Is there a better way?

Answer Source

Yes there is. Use preg_replace_callback():

header('Content-Type: text/plain');

$text = 'word1 some more words. word2 and some more words';
$text = preg_replace_callback('!\w+!', 'filter_bad_words', $text);
echo $text;

$bad_words = array(
  'word1' => 'gosh',
  'word2' => 'darn',

function filter_bad_words($matches) {
  global $bad_words;
  $replace = $bad_words[$matches[0]];
  return isset($replace) ? $replace : $matches[0];

That is a simple filter but it has many limitations. Like it won't stop variations on spelling, use of spaces or other non-word characters in between letters, replacement of letters with numbers and so on. But how sophisticated you want it to be is up to you basically.

UPDATE (9/11/2016)

I realize this is 7 years old, but newer versions of php seem to throw an exception if the word being tested is not in the $bad_words array. To fix this, I have changed the last two lines of filter_bad_words() as follows:

$replace = array_key_exists($matches[0], $bad_words) ? $bad_words[$matches[0]] : false;
return $replace ?: $matches[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download