We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

oso96_2000 on 05/19/08


Tagged

regex replace censor


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

romanos


Censor bad words with regexp


Published in: PHP 


URL: http://blog.otaku-anime.com/2008/04/29/filtro-de-palabras-en-php/

This function uses the power of regexp to check if some bad word are on the text, also offers the posibility to change those word for something else. Examples:

$texto = 'fuck off!'; filtrado($texto); returns true since a bad word has been found on the text filtrado($texto, '[censored]'); //returns [censored] off!

And because regexp, this will work with something like "fck off!". You can see a more detailed example here: http://www.otaku-anime.com/varios/filtro.php -- Example http://www.otaku-anime.com/varios/filtro.php?source -- Source code of the example

  1. <?php
  2. function filtrado($texto, $reemplazo = false)
  3. {
  4. $filtradas = 'fu?ck, shit'; //Define here your words to censor separated by comma (sorry for the badwords, it's just an example)
  5.  
  6. $f = explode(',', $filtradas);
  7. $f = array_map('trim', $f);
  8. $filtro = implode('|', $f);
  9.  
  10. return ($reemplazo) ? preg_replace("#$filtro#i", $reemplazo, $texto) : preg_match("#$filtro#i", $texto) ;
  11. }
  12. ?>

Report this snippet 

You need to login to post a comment.