-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathpad_right.php
54 lines (49 loc) · 1.29 KB
/
pad_right.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
<?php
declare(strict_types=1);
namespace Psl\Str;
/**
* Returns the string padded to the total length by appending the `$pad_string`
* to the right.
*
* If the length of the input string plus the pad string exceeds the total
* length, the pad string will be truncated. If the total length is less than or
* equal to the length of the input string, no padding will occur.
*
* Example:
*
* Str\pad_right('Ay', 4)
* => Str('Ay ')
*
* Str\pad_right('Ay', 5, 'y')
* => Str('Ayyyy')
*
* Str\pad_right('Yee', 4, 't')
* => Str('Yeet')
*
* Str\pad_right('مرحبا', 8, 'ا')
* => Str('مرحباااا')
*
* @param non-empty-string $pad_string
* @param int<0, max> $total_length
*
* @pure
*/
function pad_right(
string $string,
int $total_length,
string $pad_string = ' ',
Encoding $encoding = Encoding::Utf8,
): string {
do {
$length = length($string, $encoding);
if ($length >= $total_length) {
return $string;
}
/** @var int<0, max> $remaining */
$remaining = $total_length - $length;
if ($remaining <= length($pad_string, $encoding)) {
$pad_string = slice($pad_string, 0, $remaining, $encoding);
}
$string .= $pad_string;
} while (true);
}