Jordie
Jordie

Reputation: 899

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?

Upvotes: 2

Views: 7230

Answers (3)

cletus
cletus

Reputation: 625007

Yes there is. Use preg_replace_callback():

<?php
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];

Upvotes: 3

davethegr8
davethegr8

Reputation: 11595

Like so:

function clean($array, $str) {
    $words = array_keys($array);
    $replacements = array_values($array);

    return preg_replace($words, $replacements, $str);
}

Upvotes: 0

pix0r
pix0r

Reputation: 31280

str_ireplace() can take an array for both search and replace arguments. You can use it with your existing array like this:

$unfiltered_string = "gosh and darn are bad words";
$filtered_string = str_ireplace(array_vals($bad_words), array_keys($bad_words), $unfiltered_string);

// $filtered string now contains: "word1 and word2 are bad words"

Upvotes: 1

Related Questions