forked from muglug/psl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplit.php
60 lines (47 loc) · 1.63 KB
/
split.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
declare(strict_types=1);
namespace Psl\Str;
use Psl;
use Psl\Math;
/**
* Returns an array containing the string split on the given delimiter. The vec
* will not contain the delimiter itself.
*
* If the limit is provided, the array will only contain that many elements, where
* the last element is the remainder of the string.
*
* @throws Psl\Exception\InvariantViolationException If a negative $limit is given.
* @throws Psl\Exception\InvariantViolationException If an invalid $encoding is provided.
*
* @return list<string>
*
* @pure
*/
function split(string $string, string $delimiter, ?int $limit = null, ?string $encoding = null): array
{
Psl\invariant(null === $limit || $limit >= 1, 'Expected a non-negative limit');
if ('' === $delimiter) {
if (null === $limit || $limit >= length($string, $encoding)) {
return chunk($string, 1, $encoding);
}
if (1 === $limit) {
return [$string];
}
$result = chunk(slice($string, 0, $limit - 1, $encoding), 1, $encoding);
$result[] = slice($string, $limit - 1, null, $encoding);
return $result;
}
$limit ??= Math\INT64_MAX;
$tail = $string;
$chunks = [];
$position = search($tail, $delimiter, 0, $encoding);
while (1 < $limit && null !== $position) {
$result = slice($tail, 0, $position, $encoding);
$chunks[] = $result;
$tail = slice($tail, length($result, $encoding) + length($delimiter, $encoding), null, $encoding);
$limit--;
$position = search($tail, $delimiter, 0, $encoding);
}
$chunks[] = $tail;
return $chunks;
}