1 <?php
2 3 4
5
6
7 8 9 10 11 12 13 14 15 16 17 18 19
20 function utf8_str_pad($input, $length, $padStr = ' ', $type = STR_PAD_RIGHT) {
21
22 $inputLen = utf8_strlen($input);
23 if ($length <= $inputLen) {
24 return $input;
25 }
26
27 $padStrLen = utf8_strlen($padStr);
28 $padLen = $length - $inputLen;
29
30 if ($type == STR_PAD_RIGHT) {
31 $repeatTimes = ceil($padLen / $padStrLen);
32 return utf8_substr($input . str_repeat($padStr, $repeatTimes), 0, $length);
33 }
34
35 if ($type == STR_PAD_LEFT) {
36 $repeatTimes = ceil($padLen / $padStrLen);
37 return utf8_substr(str_repeat($padStr, $repeatTimes), 0, floor($padLen)) . $input;
38 }
39
40 if ($type == STR_PAD_BOTH) {
41
42 $padLen/= 2;
43 $padAmountLeft = floor($padLen);
44 $padAmountRight = ceil($padLen);
45 $repeatTimesLeft = ceil($padAmountLeft / $padStrLen);
46 $repeatTimesRight = ceil($padAmountRight / $padStrLen);
47
48 $paddingLeft = utf8_substr(str_repeat($padStr, $repeatTimesLeft), 0, $padAmountLeft);
49 $paddingRight = utf8_substr(str_repeat($padStr, $repeatTimesRight), 0, $padAmountLeft);
50 return $paddingLeft . $input . $paddingRight;
51 }
52
53 trigger_error('utf8_str_pad: Unknown padding type (' . $type . ')',E_USER_ERROR);
54 }
55