Created
July 25, 2015 09:40
-
-
Save 3zzy/322e488c6ac72035ab3d to your computer and use it in GitHub Desktop.
strpos multiple needles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function strpos_array($haystack, $needles, $offset=0) { | |
$matches = array(); | |
//Avoid the obvious: when haystack or needles are empty, return no matches | |
if(empty($needles) || empty($haystack)) { | |
return $matches; | |
} | |
$haystack = (string)$haystack; //Pre-cast non-string haystacks | |
$haylen = strlen($haystack); | |
//Allow negative (from end of haystack) offsets | |
if($offset < 0) { | |
$offset += $heylen; | |
} | |
//Use strpos if there is no array or only one needle | |
if(!is_array($needles)) { | |
$needles = array($needles); | |
} | |
$needles = array_unique($needles); //Not necessary if you are sure all needles are unique | |
//Precalculate needle lengths to save time | |
foreach($needles as &$origNeedle) { | |
$origNeedle = array((string)$origNeedle, strlen($origNeedle)); | |
} | |
//Find matches | |
for(; $offset < $haylen; $offset++) { | |
foreach($needles as $needle) { | |
list($needle, $length) = $needle; | |
if($needle == substr($haystack, $offset, $length)) { | |
$matches[] = $offset; | |
break; | |
} | |
} | |
} | |
return($matches); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment