How to Replace banned words using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Replace banned words using PHP

Post by Tony » Sun Nov 29, 2009 4:57 am

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);
?>
Post Reply

Return to “PHP & MySQL”