Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find needle in haystack, where needle is array of needles

Tags:

php

I have a function that takes a string (the haystack) and an array of strings (the needles) and returns true if at least one needle is a substring of the haystack. It didn't take much time or effort to write it, but I'm wondering if there's a PHP function that already does this.

function strstr_array_needle($haystack, $arrayNeedles){
    foreach($arrayNeedles as $needle){
        if(strstr($haystack, $needle)) return true;
    }
    return false;    
}
like image 443
Drahcir Avatar asked Dec 21 '11 21:12

Drahcir


2 Answers

just a suggestion...

function array_strpos($haystack, $needles)
{
    foreach($needles as $needle)
        if(strpos($haystack, $needle) !== false) return true;
    return false;
}
like image 171
Dejan Marjanović Avatar answered Nov 12 '22 21:11

Dejan Marjanović


I think the closest function would be array_walk_recursive(), but that requires a callback. So using it would probably be more complicated than what you already have.

like image 25
Brian Avatar answered Nov 12 '22 20:11

Brian