Forum Moderators: coopster

Message Too Old, No Replies

Searching for bunch of needles in a haystack

Question about searching a string

         

muumipeikko

11:14 pm on Jul 19, 2008 (gmt 0)

10+ Year Member



Hello,

I'm looking for a way to search possible occurrences of multiple different needles in a haystack and then act on it if any of them appear. So if I have a $haystack that says "Lorem ipsum dolor sit amet" and my list of needles contain words "badger, tractor, quarterback" it would return false, but true if my $haystack is "Typical badgers are short-legged and heavy-set."

MattAU

11:39 pm on Jul 19, 2008 (gmt 0)

10+ Year Member



Something like this should do the trick:

function my_search($haystack,$needles)
{
foreach($needles as $needle)
{
if(strpos($haystack,$needle) !== false)
return true;
}
return false;
}

It checks each needle from the given array of needles, returns true with the first occurance found, or returns false if none are found. If $needles contains a string of comma separated values then you'll need to use split() before hand to turn it into an array.