1 | <?php |
---|
2 | |
---|
3 | /** |
---|
4 | * @version $Id: str_pad.php,v 1.1 2006/09/03 09:25:13 harryf Exp $ |
---|
5 | * @package utf8 |
---|
6 | * @subpackage strings |
---|
7 | */ |
---|
8 | |
---|
9 | /** |
---|
10 | * Replacement for str_pad. $padStr may contain multi-byte characters. |
---|
11 | * |
---|
12 | * @author Oliver Saunders <oliver (a) osinternetservices.com> |
---|
13 | * @param string $input |
---|
14 | * @param int $length |
---|
15 | * @param string $padStr |
---|
16 | * @param int $type ( same constants as str_pad ) |
---|
17 | * @return string |
---|
18 | * @see http://www.php.net/str_pad |
---|
19 | * @see utf8_substr |
---|
20 | * @package utf8 |
---|
21 | * @subpackage strings |
---|
22 | */ |
---|
23 | function utf8_str_pad($input, $length, $padStr=' ', $type=STR_PAD_RIGHT) |
---|
24 | { |
---|
25 | $inputLen = utf8_strlen($input); |
---|
26 | if ($length <= $inputLen) |
---|
27 | return $input; |
---|
28 | |
---|
29 | $padStrLen = utf8_strlen($padStr); |
---|
30 | $padLen = $length - $inputLen; |
---|
31 | |
---|
32 | if ($type == STR_PAD_RIGHT) |
---|
33 | { |
---|
34 | $repeatTimes = ceil($padLen / $padStrLen); |
---|
35 | return utf8_substr($input.str_repeat($padStr, $repeatTimes), 0, $length); |
---|
36 | } |
---|
37 | |
---|
38 | if ($type == STR_PAD_LEFT) |
---|
39 | { |
---|
40 | $repeatTimes = ceil($padLen / $padStrLen); |
---|
41 | return utf8_substr(str_repeat($padStr, $repeatTimes), 0, floor($padLen)).$input; |
---|
42 | } |
---|
43 | |
---|
44 | if ($type == STR_PAD_BOTH) |
---|
45 | { |
---|
46 | $padLen /= 2; |
---|
47 | $padAmountLeft = floor($padLen); |
---|
48 | $padAmountRight = ceil($padLen); |
---|
49 | $repeatTimesLeft = ceil($padAmountLeft / $padStrLen); |
---|
50 | $repeatTimesRight = ceil($padAmountRight / $padStrLen); |
---|
51 | |
---|
52 | $paddingLeft = utf8_substr(str_repeat($padStr, $repeatTimesLeft), 0, $padAmountLeft); |
---|
53 | $paddingRight = utf8_substr(str_repeat($padStr, $repeatTimesRight), 0, $padAmountLeft); |
---|
54 | |
---|
55 | return $paddingLeft.$input.$paddingRight; |
---|
56 | } |
---|
57 | |
---|
58 | trigger_error('utf8_str_pad: Unknown padding type ('.$type.')', E_USER_ERROR); |
---|
59 | } |
---|