PHP Tutorial : Function – Filter unwanted words

Hello,

I finded it usefull to build a simple and maximum 10 lines of code php function which can be used in filtering words that you wouldn’t want to appear on your website, forum, guestbook, comments, etc.

The most common way where is to use it within a html form, validating an input, textarea element, etc.

The code is built and commented below :

<?php
//call the special word which builds a new function

//custom php function and give it a nice name
function filterMe($whatToFilter, $listOfUnwantedWords)
{

foreach ($listOfUnwantedWords as $value) {

if (preg_match("/$value/i", "$whatToFilter")) {

print "You have used an unallowed word";
exit();
}
}
}
?>

Usage of this php function to filter unwanted words : firstly, build an php array with unwanted words, then apply the function where you need it. Example :

<?php
//create array with not wanted words

$Unwanted = array("www", "mywebsite", "etc");
//estabilish which given word to filter

$word = $_POST['yourinput'];
//function in action


filterMe($word, $Unwanted);
?>

Feel free to use it anywhere!

This entry was posted in Short PHP Functions and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>