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?
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?
Yes there is. Use preg_replace_callback()
:
'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.
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];
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"
Like so:
function clean($array, $str) { $words = array_keys($array); $replacements = array_values($array); return preg_replace($words, $replacements, $str); }