Page 1 of 1

How to Replace banned words using PHP

Posted: Sun Nov 29, 2009 4:57 am
by Tony
This script will replace banned words in the string $message with an * for each letter. You can use this when receiving POST data with text input. In this example the banned words are in a text file called words.dat (in the same directory as the script) with one banned word per line.

Code: Select all

<?php
$words_array = preg_replace("#\r\n?|\n#","",file('words.dat'));  // read the file into an array and remove new line breaks (should cover all OS)
$word_stars = preg_replace( '/./','*',$words_array ); // replace every letter with a *
$words_array = preg_replace( '/(.+)/','#\1#i',$words_array ); // put # delim around each word
$message = preg_replace($words_array,$word_stars,$message);
?>