Search code examples
phparraysstringstrpos

PHP check string for any array items


I have an array of say 4 strings. How do i check to see if ANY of them are in a string and then return a true value if ANY are found in the string.

Have tried strpos() but for that, the needle has to be a string or integer, and cannot be an array.

Is there a case-insensitive way other than checking each array item separately via a loop through the array?

Example text:

$string = "A rural position on a working dairy farm but within driving distance 
of the sea and local villages, also sharing an indoor pool";

$arr = array("farm", "Working farm", "swimming pool", "sea views");

Solution

  • The best way would be to loop through the array of needles and check if it is found in the string:

    function stripos_a($arr, $string) {
        foreach ($arr as $search) {
            if (stripos($string, $search) !== false) return true;
        }
        return false;
    }
    

    Test:

    var_dump(stripos_a($arr, $string)); // bool(true)
    

    Demo.