-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
strip_suffix.php
43 lines (35 loc) · 1.02 KB
/
strip_suffix.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
<?php
declare(strict_types=1);
namespace Psl\Str\Byte;
/**
* Returns the string with the given suffix removed, or the string itself if
* it doesn't end with the suffix.
*
* @pure
*/
function strip_suffix(string $string, string $suffix): string
{
if ($string === '' || $suffix === '') {
return $string;
}
if ($string === $suffix) {
return '';
}
$suffix_length = length($suffix);
$string_length = length($string);
// if $suffix_length is greater than $string_length, return $string as it can't contain $suffix.
// if $suffix_length and $string_length are the same, return $string as $suffix is not $string.
if ($suffix_length >= $string_length) {
return $string;
}
if (!ends_with($string, $suffix)) {
return $string;
}
/**
* $string_length is greater than $suffix_length, so the result is always int<0, max>.
*
* @var int<0, max> $length
*/
$length = $string_length - $suffix_length;
return slice($string, 0, $length);
}