2

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?

Siguza
  • 21,155
  • 6
  • 52
  • 89
Jordie
  • 899
  • 2
  • 11
  • 20

3 Answers3

3

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];
Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942
0

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"
pix0r
  • 31,139
  • 18
  • 86
  • 102
  • 1
    The problem with that is that you can make replacements on partial words. Imagine "butt" was a bad word in this case, well you'll replace it in "buttress", which is a completely unrelated word. – cletus Jun 19 '09 at 23:34
  • Indeed - this is just the simplest solution. preg_replace_callback() would work better. – pix0r Jun 19 '09 at 23:36
  • Yes sorry i dont want cbuttic cars – Jordie Jun 19 '09 at 23:50
-1

Like so:

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

    return preg_replace($words, $replacements, $str);
}
davethegr8
  • 11,323
  • 5
  • 36
  • 61