-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathleft-pad.php
More file actions
45 lines (41 loc) · 1.22 KB
/
left-pad.php
File metadata and controls
45 lines (41 loc) · 1.22 KB
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
<?php
if (!function_exists('left_pad')) {
/**
* Left-pad a string
*
* @param string $str
* @param int $length
* @param string $space
* @param string $encoding
* @return string
*/
function left_pad($str, $length = 0, $space = ' ', $encoding = '8bit')
{
if (is_array($str)) {
return array_left_pad($str, $length, $space);
}
if (function_exists('mb_strlen')) {
while (mb_strlen($str, $encoding) < $length) {
$padLength = mb_strlen($str, $encoding);
if ($padLength < mb_strlen($space, $encoding)) {
$str = mb_substr($space, 0, $padLength, $encoding) . $str;
} else {
$str = $space . $str;
}
}
return $str;
}
return str_pad($str, $length, $space, STR_PAD_LEFT);
}
function array_left_pad($array, $length, $space)
{
if (! is_int($length) and function_exists('count')) {
$length = count($array);
}
$padded = [];
while ($length-- > 0) {
$padded[$length] = $space;
}
return $padded + $array;
}
}