Hi using the example below, how would I modify the code if the $needle was a list instead of a single string? Ie I want to establish if any one of the items from a list are contained within the $haystack as opposed to just one single string. Say there where 3 $needles, $needle = ‘other’ $needle = ‘the’ $needle = ‘moth’ thank you for any help
If $needle is an array, simply walk through the array using strpos(), i.e. <?php $needles=array("Moe","Larry","Curly","Shemp","Joe","Curly Joe"); foreach ($needles as $needle) { $pos=strpos($haystack,$needle); if($pos) print "Yahoo!\n"; }
If you don't mind a little overhead in your script, I like this approach: $needles = array ('one', 'two', 'three'); $needles_regex = '![' . explode('|', $needles) . ']!'; if (preg_match($needles_regex, $haystack, $matches)) { // one or more needles were found } PHP:
Until you're $needles contain something like |, [, ], (, ) or / and break your RegEx... (I assume you meant to use implode rather than explode...)
yea.. also, if your string is multiline, you'll need some Perl modifier for the pattern, which i don't remember exactly. anyway, its an idea, not a solution..
thanks all for your help, still a novice at PHP ... after all these years. Modified the code to do exactly what I wanted with your advice. Can track my warehouse traffic now : )