Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Created January 5, 2016 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lewiscowles1986/4bf60c377771e8c7b581 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/4bf60c377771e8c7b581 to your computer and use it in GitHub Desktop.
find all offsets in a string
<?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