PHP,str_pad unicode 问题

标签 php string unicode

我只是想将 $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 .

有这方面的经验吗?

谢谢。

最佳答案

您需要一个多字节版本的 str_pad(),如下所示。它的灵感来自 source code of str_pad() .

function mb_str_pad($input, $pad_length, $pad_string = ' ', $pad_type = STR_PAD_RIGHT, $encoding = 'UTF-8')
{
    $input_length = mb_strlen($input, $encoding);
    $pad_string_length = mb_strlen($pad_string, $encoding);

    if ($pad_length <= 0 || ($pad_length - $input_length) <= 0) {
        return $input;
    }

    $num_pad_chars = $pad_length - $input_length;

    switch ($pad_type) {
        case STR_PAD_RIGHT:
            $left_pad = 0;
            $right_pad = $num_pad_chars;
            break;

        case STR_PAD_LEFT:
            $left_pad = $num_pad_chars;
            $right_pad = 0;
            break;

        case STR_PAD_BOTH:
            $left_pad = floor($num_pad_chars / 2);
            $right_pad = $num_pad_chars - $left_pad;
            break;
    }

    $result = '';
    for ($i = 0; $i < $left_pad; ++$i) {
        $result .= mb_substr($pad_string, $i % $pad_string_length, 1, $encoding);
    }
    $result .= $input;
    for ($i = 0; $i < $right_pad; ++$i) {
        $result .= mb_substr($pad_string, $i % $pad_string_length, 1, $encoding);
    }

    return $result;
}


$str = "nü";
$pad = "ü";

echo mb_str_pad($str, 5, $pad);

关于PHP,str_pad unicode 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14773072/

相关文章:

php - Laravel JWT - 使用 Javascript 使用你自己的 API

c# 替换字符串函数不返回预期结果

ms-access - 使用波形符分隔符将 MSAccess 表导出为 Unicode

javascript - 如何在javascript中处理python unicode字符串?

PHP-GD : Dealing with Unicode characters

php - 使用 php session 加载 Jquery 内容

php - 如何使用 PDO 避免 mysql 注入(inject)

php - 如何从 mysql 为 highcharts 创建正确的 json 数据格式

c++ - 计算字符串中单个单词的长度

java - 如何在 Java 中将字符串转换回对象列表