in src/regex/regex.php [187:227]
function split(
string $haystack,
Pattern<Match> $delimiter,
?int $limit = null,
)[]: vec<string> {
if ($limit === null) {
$limit = \INF;
}
invariant(
$limit > 1,
'Expected limit greater than 1, got %d.',
$limit,
);
$haystack_length = Str\length($haystack);
$result = vec[];
$offset = 0;
$match_end = 0;
$count = 1;
$match = _Private\regex_match($haystack, $delimiter, inout $offset);
while ($match && $count < $limit) {
// Copy anything between the previous match and this one
$result[] = Str\slice($haystack, $match_end, $offset - $match_end);
$match_length = Str\length(Shapes::at($match, 0) as string);
$match_end = $offset + $match_length;
if ($match_length === 0) {
// To get the next match (and avoid looping forever), need to skip forward
// before searching again
// Note that `$offset` is for searching and `$match_end` is for copying
$offset++;
if ($offset > $haystack_length) {
break;
}
} else {
$offset = $match_end;
}
$count++;
$match = _Private\regex_match($haystack, $delimiter, inout $offset);
}
$result[] = Str\slice($haystack, $match_end);
return $result;
}