Page 1 of 1

Censoring Words with PHP - Help Needed!

Posted: Sat Oct 06, 2007 4:55 am
by dtcapener
Hey, my first post! lol

anyway, i have a website with videos on it and i have a comment system where people can comment the video below.

Now the problem is that, people seem to be swearing in their comments they post, and i would like to be able to censor these bad words so it would like leave the first letter and last letter of the word viewable, but censor out the middle letters with a *

Basically all i need is a piece of code which i can insert into that document with the comments on and when a visitor loads that page the bad words will be censored.

The thing is though the comments are saved in a MySQL database, so i have really no idea on how to go about this! (if that would make a difference to it anyway!)


I would really aprieciate any help with this one please :)

Thanks in advanced,
dtcapener

Posted: Sat Oct 06, 2007 5:10 am
by stereofrog
Hi, welcome to the forums

Code: Select all

$text = "a message with a bad word in it";
$bad_words = array('message', 'word'); // put bad words here
$clean_text = preg_replace(
	"~\\b(" . implode("|", $bad_words) . ")\\b~e", 
	"substr('$0',0,1).str_repeat('*',strlen('$0')-2).substr('$0',-1,1)",
	$text);

Posted: Sat Oct 06, 2007 5:21 am
by dtcapener
Thanks so much!
very fast reply, im impressed

ill see what i can do!
think i can get this to work with my site!

thanks!
dtcapener

Posted: Sat Oct 06, 2007 9:02 am
by feyd
I'd run preg_quote() over that array before imploding. Also, I'd switch to preg_replace_callback() instead of using an evaluate modifier -- potential security issues, although unlikely.