Created
January 5, 2016 15:39
-
-
Save Lewiscowles1986/4bf60c377771e8c7b581 to your computer and use it in GitHub Desktop.
find all offsets in a string
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 offsetsIn(string $haystack, string $needle, $cs=true) : array { | |
$offset = false; | |
$pos = 0; | |
$out = []; | |
$func = $cs ? '\strpos' : '\stripos'; | |
while (strlen($haystack) > 0 && ($pos === 0 || $offset !== false)) { | |
if($offset !== false) { | |
$out[] = $offset; | |
} | |
$offset = $func($haystack,$needle,$pos); | |
$pos = $offset ? $offset+1 : $pos+1; | |
} | |
return $out; | |
} | |
// | |
// Tests | |
// | |
$testData = [ | |
offsetsIn("abcdeaaaafghia", 'a'), | |
offsetsIn("bcdeaaaafghia", 'a'), | |
offsetsIn("bcdefghia", 'a'), | |
offsetsIn("abcdeaaaafghi", 'a'), | |
offsetsIn("abcdeafghia", 'a'), | |
offsetsIn("bcdefghi", 'a'), | |
]; | |
assert( count( $testData[0] ) === 6); | |
assert( count( $testData[1] ) === 5); | |
assert( count( $testData[2] ) === 1); | |
assert( count( $testData[3] ) === 5); | |
assert( count( $testData[4] ) === 3); | |
assert( count( $testData[5] ) === 0); | |
foreach($testData as $testR) { | |
assert( is_array($testR) === true ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment