我只是试图将$str固定为5个字符,但不能.
$str = "nü"; echo str_pad($str,5,"ü"); // give nüü
我知道这是一个unicode的问题,搜索了很多,但没有运气.我尝试过某些事情,如;
echo str_pad($str,4 + mb_strlen($s),$s); echo str_pad($str,5 + mb_strlen($s),$s);
我也试过这个http://www.php.net/manual/de/function.str-pad.php#89754,看到这个https://stackoverflow.com/a/11871948/362780.
关于这个问题的任何经验?
谢谢.
我想你需要看更多PHP.net(这里:
http://php.net/str_pad#111147).但我改变了一点.
原文链接:https://www.f2er.com/php/132682.html注意:不要忘记在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),floor($length)) . $str . mb_substr(str_repeat($pad_str,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,$pad_len); } else if ($dir == STR_PAD_LEFT) { $result = str_repeat($pad_str,$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,$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>";