How do I replace bad words with php?

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

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?

回答1:

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.

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


回答2:

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" 


回答3:

Like so:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!