Filed Under: Code Snippets, PHP

Find occurences of multiple needles in haystack

17 October 2008 No Comment

Let’s say you got a form and you don’t want to allow that people submit certain words. How would you do that? Right you will have to use the PHP function strpos. Unfortunately you can’t feed strpos with arrays (a list of needles)!

Here is a very simple solution that you can use to to check multiple needles and their occurence in a specific string.

 
$haystack = $myhaystack;
$needle = array('badword','badword','badword','badword');
 
foreach($needle as $value){
$pos = strpos($haystack, $value);
if ($pos !== false){ /* If we find one of those bad words do the following */
 
	header("Location: http://mysite.com?error=badcontent");
	exit;
 
	}
}

I used the “header” command to redirect people to a specific site if they enter those bad words. You can output a customized error message by adding a variable at the end of the URL e.g. the variable “error”. Simply retrieve the variable via GET and then echo an appropriate message.

If you have any question feel free to ask!

Enjoy :)







Like our posts? Then subscribe via Mail:

Email:  

Similar Posts:

Socialize:

delicious stumbleupon

Leave your response!

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.com.