Skip to content

Instantly share code, notes, and snippets.

@irazasyed
Created July 12, 2013 17:21
Show Gist options
  • Save irazasyed/5986152 to your computer and use it in GitHub Desktop.
Save irazasyed/5986152 to your computer and use it in GitHub Desktop.
PHP: Strpos Array, Find in array!
<?php
/* strpos that takes an array of values to match against a string note the stupid argument order (to match strpos) */
function strpos_arr($haystack, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false) return $pos;
}
return false;
}
@andres3210
Copy link

andres3210 commented Sep 10, 2020

Hey, you need to check for the FIRST occurence form all characters. Your current logic gives you the first occurrence of the top array elements. Here is the corrected logic:

function strpos_arr($haystack, $needle) {
        if( !is_array($needle) ) $needle = array($needle);
        $min = false;
        foreach($needle as $what) 
            if( ($pos = strpos($haystack, $what)) !== false && ($min == false || $pos < $min) ) 
                $min = $pos;
        return $min;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment