You are here: HomeForums » PHP » Regex » Regex to censor bad words

Regex to censor bad words (1 post)

in Forums » PHP » Regex
  • Started 1 month ago by thdadmin

thdadmin (administrator)

The following is a very usefull and simple function that uses regex to search for matches of words you want censored and replaces them with a word specified as a parameter.
The functions looks like this:

<?php

function filterCensored($text, $replacement = false)
{
	$badWords = 'damn, crap'; // The words you want to censor

	$f = explode(',', $badWords);
	$f = array_map('trim', $f);
	$filter = implode('|', $f);

	return ($replacement) ? preg_replace("#$filter#i", $replacement, $text) : preg_match("#$filter#i", $text) ;
}

?>

The function returns either the string with the replaced bad words if the second parameter exists, or the true or false if it doesn't. True means bad words were found, and false means the text doesn't contain censored words.
Have a look at the following example to see how easy it is to use this function:

<?php

echo filterCensored('I don't give a damn', 'd**n');

?>

This will return the string 'I don't give a d**n'.
Because the function uses regex, you can use regex when you define the filter.
There are come improved versions of this functions. I you can think of anything let me know ;)

Posted 1 month ago #

Reply

You must log in to post.