Censoring Words with PHP - Help Needed!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dtcapener
Forum Newbie
Posts: 2
Joined: Fri Oct 05, 2007 5:22 pm

Censoring Words with PHP - Help Needed!

Post 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
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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);
dtcapener
Forum Newbie
Posts: 2
Joined: Fri Oct 05, 2007 5:22 pm

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Post Reply