forked from muglug/psl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slice.php
31 lines (25 loc) · 845 Bytes
/
slice.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
<?php
declare(strict_types=1);
namespace Psl\Str\Byte;
use Psl;
use function substr;
/**
* Returns a substring of length `$length` of the given string starting at the
* `$offset`.
*
* If no length is given, the slice will contain the rest of the
* string. If the length is zero, the empty string will be returned.
*
* @pure
*
* @throws Psl\Exception\InvariantViolationException If $length is negative, or the $offset is out-of-bounds.
*/
function slice(string $string, int $offset, ?int $length = null): string
{
Psl\invariant(null === $length || $length >= 0, 'Expected a non-negative length.');
$offset = Psl\Internal\validate_offset($offset, length($string));
$result = null === $length
? substr($string, $offset)
: substr($string, $offset, $length);
return false === $result ? '' : $result;
}