Search code examples
phpstrpos

strpos store all results not first positive


I have this code.

$needles = explode(" ", $textContentArray); 
$haystack = $textContent; 
$match_found = strposa($haystack,$needles);
if($match_found) {
    echo $match_found ; 
}
else {
    echo "No match found.";
}

function strposa($haystack, $needles) { 
$chr = array();
foreach($needles as $needle) {
    $res = stripos($haystack, $needle);
    if ($res !== false)
        {
            $chr[$needle] = $res;
            $string_exist = $needle; break; 
        }
    }
    if(empty($chr)) return false; 
    return $string_exist;
}

Currently this outputs the first match it finds, however, I'd like it to output every match not just the first. This is because I'm using it on a site which will show any string matches between 2 url's.

Thank you.


Solution

  • just return matches in your function

        if(empty($chr)) return false; 
        return $chr;
    }
    

    and remove break

    so $match_found will be array for example ["foo" => 1, "bar" => 4, ...]