Lots of websites nowadays have incorporated interactive features, such as
blogs, comments, views, etc. These allow visitors to post their comments online.
While it's good to have such features, they can also become a liability when
users start posting offensive or derogatory comments on the website. That
ultimately affects the website's reputation.
If you are also struggling to save your website's reputation, then here's a
simple way out.
In this article, we provide you a PHP code snippet that will help you stop
banned words from being posted on your website or blog, by anonymous visitors.
Direct Hit! |
Applies To: PHP developers USP: Prevent offensive language from appearing on your site Primary Link: www.php.net Keywords: Language filter |
First of all, list down all words in a text file that you want to ban. Then,
write down a function 'check_offensive_ word()', which will be responsible for
checking each word written on your website for being an offensive word.The code
for the same is as follows:
function language_filter($string) {
$offensive = @file("path/to/your/file/bad_lang.dat");
foreach ($offensive as $curse_word) {
if (stristr(trim($string),$curse_word)) {
$length = strlen($curse_word);
for ($i = 1; $i <= $length; $i++) {
$stars .= "*";
}
$string = ereg_replace($curse_word,$stars,trim($string));
$stars = "";
}
}
return $string;
}
?>
The PHP script that you'll create will check all content on your web page against a banned list you've created. Any matches it finds are automatically replaced with a '*' |
When the string is passed to this function, the string is parsed and checked
for any offensive word that you have specified in the file 'bad_lang.dat'. It
takes a word at a time from the string and checks if the word is present in the
'bad_lang.dat'. If the word is present in the list of offensive words then it
simply calculates the length of the word and replaces it with a sequence of
'*'s.
The 'ereg_replace' is an in-built function in PHP which replaces offensive
words with the character you define, which in this case is '*'.
For testing this, write the following code snippet:
$string = "test for offensive words.";
print language_filter($string);
?>
If you have defined the word 'offensive' in your banned words list, then the
output of the above code will be:
Test for ********* words.
This little code will make your webpages a little cleaner.