我认为你需要更多地 php.net(这里:http://php.net/str_pad#111147)。但是我稍微改变了一下。
注意:不要忘记在之前调用它。mb_internal_encoding("utf-8");
mb_internal_encoding("utf-8");
function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
$str_len = mb_strlen($str);
$pad_str_len = mb_strlen($pad_str);
if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
$str_len = 1; // @debug
}
if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
return $str;
}
$result = null;
if ($dir == STR_PAD_BOTH) {
$length = ($pad_len - $str_len) / 2;
$repeat = ceil($length / $pad_str_len);
$result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length))
. $str
. mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
} else {
$repeat = ceil($str_len - $pad_str_len + $pad_len);
if ($dir == STR_PAD_RIGHT) {
$result = $str . str_repeat($pad_str, $repeat);
$result = mb_substr($result, 0, $pad_len);
} else if ($dir == STR_PAD_LEFT) {
$result = str_repeat($pad_str, $repeat);
$result = mb_substr($result, 0,
$pad_len - (($str_len - $pad_str_len) + $pad_str_len))
. $str;
}
}
return $result;
}
$t = STR_PAD_LEFT;
$s = '...';
$as = 'AO';
$ms = 'ÄÖ';
echo "<pre>\n";
for ($i = 3; $i <= 1000; $i++) {
$s1 = str_pad($s, $i, $as, $t); // can not inculde unicode char!!!
$s2 = str_pad_unicode($s, $i, $ms, $t);
$l1 = strlen($s1);
$l2 = mb_strlen($s2);
echo "len $l1: $s1 \n";
echo "len $l2: $s2 \n";
echo "\n";
if ($l1 != $l2) die("Fail!");
}
echo "</pre>";
在此测试:http://codepad.viper-7.com/3jTEgt