This time I want to build a function that can detect undesired words contained in a message. This function could be very usefull when you want to build a guestbook or a chat. Infact you can prevent the displaying of messages containing undesired words. But now we atake a look to the code. The function will be called 'check'.   
<?    
function check($text)    
{    
$undesired_words=array("cat","dog");    
$result=0;    
$dim=count($undesired_words);    
for ($i=0;$i<$dim;$i++)    
{    
if (stristr($text,$undesired_words[$i]))    
{    
$result=1;    
}    
}     
return $result;    
} 
$message="Today I went away with my dog for a walk";   
if (check($message)) echo "There are undesired words in the message"; else echo "All it's ok";    
?>
A comment on the code:    
The function chek has as argument the message that we want to analyze. We build an array called undesired_words containing the undesired words, in this case thay are cat and dog. The variable $result is a flag whos value is 1 if it was found an undesired word else her value is 0. The cycle for scans all the words in the array undesired_words while the php function stristr detect if the word is contained in the message. To control the validity of the function 'check' we insert into the variable $message a message and with an if we control the validity of the 'check' function.    
This example can be used as a base to build a system that block the displaying of messages in your php applications.
Article written by the webmaster of Tuttophp
 
 
No comments:
Post a Comment