Last active
June 28, 2022 20:15
-
-
Save msng/5039773 to your computer and use it in GitHub Desktop.
PHP: strpos_array is strpos that can take an array as needle
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
<?php | |
function strpos_array($haystack, $needles, $offset = 0) { | |
if (is_array($needles)) { | |
foreach ($needles as $needle) { | |
$pos = strpos_array($haystack, $needle); | |
if ($pos !== false) { | |
return $pos; | |
} | |
} | |
return false; | |
} else { | |
return strpos($haystack, $needles, $offset); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a bit of an issue here.
Since you have multiple needles, it is possible that the first needle is found, but a later needle is found earlier in the string. The above function does not cover that. The below edit will adjust for it.
However this means returning an array of found needles back. If you want only the position of the first occurrence, do as so:
$cursor = reset( strpos_array( .... ) );
If you want all matches for all needles, leave the reset() call out.