fork(1) download
  1. <?php
  2.  
  3. if ( ! function_exists('word_censor'))
  4. {
  5. function word_censor($str, $censored, $replacement = '')
  6. {
  7. if ( ! is_array($censored))
  8. {
  9. return $str;
  10. }
  11.  
  12. $str = ' '.$str.' ';
  13.  
  14. // \w, \b and a few others do not match on a unicode character
  15. // set for performance reasons. As a result words like über
  16. // will not match on a word boundary. Instead, we'll assume that
  17. // a bad word will be bookeneded by any of these characters.
  18. $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
  19.  
  20. foreach ($censored as $badword)
  21. {
  22. if ($replacement != '')
  23. {
  24. $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str);
  25. }
  26. else
  27. {
  28. $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str);
  29. }
  30. }
  31.  
  32. return trim($str);
  33. }
  34. }
  35.  
  36.  
  37.  
  38. echo word_censor('Texto do comentario com um palavrao', array('palavrao'), '---');
  39. echo "\n";
  40. echo word_censor('Texto do comentario com um palavrao', array('palavrao'));
  41.  
Success #stdin #stdout 0.03s 52480KB
stdin
Standard input is empty
stdout
Texto do comentario com um ---
Texto do comentario com um ########