Filtering badword in text area


#1

I have a simple form with text area. I do not want it filled up with all kinds of badwords.

I have array like this:

$badword = array(“1bad” , “2bad” , “3bad” , “4bad”);

and…

$replacebadword = “bad***”;
foreach(badwords as $bad) {

$message = preg_replace($bad , $replacebadword , $message);

}
print “$message”;

pls help it’s not replaceing annything!. The $message is the textarea input string received from my form.

Geir


#2

The problem with the script is your use of preg_replace. Since preg_replace uses regular expressions to replace character is a string, it is not picking up on the values in your array. There are two things you can do.

First, you can make the word array regex friendly:
[php]

<?php $badword = array( "bad1", "bad2", "bad3" ); $replace = "bad***"; foreach( $badword as $bad ) { $message = preg_replace( "/". $bad ."/si", $replace, $message ); } echo $message; ?>

[/php]

Or, the easier way would be just to use str_replace:
[php]

<?php $badword = array( "bad1", "bad2", "bad3" ); $replace = "bad***"; foreach( $badword as $bad ) { $message = str_replace( $bad, $replace, $message ); } echo $message; ?>

[/php]

Hoped that helped.


#3

Thank you!

I’m using the preg_replace function now. Its working and I’m happy.

:lol: