You will learn how to create a simple PHP foul language filter function which uses a file containing foul words to replace them in the string of your choice with asterisks.
In this tutorial we will create a simple PHP function which will replace foul words with asterisks or any character or string of your choice. The list of foul words will be retrieved from a text file. Each foul word must be entered on a different line. A sample foul language file can be download at http://www.geekpedia.com/Scripts/foul.txt (reader’s discretion is advised).
Let’s view the function. It’s not too complicated and the comments should guide you through:
function LangFilter($ToFilter)
{
// Open the foul.txt for extracting the foul words
$Foul = @file("foul.txt");
// Loop through the foul words
foreach ($Foul as $FoulWord)
{
// Store the current foul word in a variable
$FoulWord = trim($FoulWord);
// If there's a match for the fould world inside the string
if (preg_match("/".$FoulWord."/i", $ToFilter))
{
// Get the word length, so that we know how many characters
// we need to replace with asterisks
$WordLength = strlen($FoulWord);
// Loop through the word's characters
for ($i = 1; $i <= $WordLength; $i++)
{
// Replace the characters of the foul word with * (asterisks)
$RepChar .= "*";
}
// Replace the dirty string with the filtered string
$ToFilter = eregi_replace($FoulWord, $RepChar, trim($ToFilter));
$RepChar = "";
}
}
// Return the new string
return $ToFilter;
}
All you really need to do for this script to work, is to place the foul.txt file in the same directory, and to call the LangFilter() function on the string that you need filtered, like in the example below:
echo LangFilter("If dirtbag would have been a dirty word, it would be replaced now by asterisks.");
Indeed, if dirtbag would’ve been on the list, the following line would output:
If ******* would have been a dirty word, it would be replaced now by asterisks.
Here is the same function but without the comments, in case you want to copy and paste it in your code, and you’re not interested in the comments.
function LangFilter($ToFilter)
{
$Foul = @file("foul.txt");
foreach ($Foul as $FoulWord)
{
$FoulWord = trim($FoulWord);
if (preg_match("/".$FoulWord."/i", $ToFilter))
{
$WordLength = strlen($FoulWord);
for ($i = 1; $i <= $WordLength; $i++)
{
$RepChar .= "*";
}
$ToFilter = eregi_replace($FoulWord, $RepChar, trim($ToFilter));
$RepChar = "";
}
}
return $ToFilter;
}