【问题标题】:Output UTF-16? A little stuck输出 UTF-16?有点卡住
【发布时间】:2011-03-31 05:40:47
【问题描述】:

我有一些 UTF-16 编码字符的代理对形式。我想将这些代理对输出为屏幕上的字符。

有人知道这怎么可能吗?

【问题讨论】:

标签: php utf-16 surrogate-pairs


【解决方案1】:

iconv('UTF-16', 'UTF-8', yourString)

【讨论】:

    【解决方案2】:

    你的问题有点不清楚。

    如果您有嵌入了 UTF-16 转义序列的 ASCII 文本,您可以通过以下方式将所有内容转换为 UTF-8:

    function unescape_utf16($string) {
        /* go for possible surrogate pairs first */
        $string = preg_replace_callback(
            '/\\\\u(D[89ab][0-9a-f]{2})\\\\u(D[c-f][0-9a-f]{2})/i',
            function ($matches) {
                $d = pack("H*", $matches[1].$matches[2]);
                return mb_convert_encoding($d, "UTF-8", "UTF-16BE");
            }, $string);
        /* now the rest */
        $string = preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
            function ($matches) {
                $d = pack("H*", $matches[1]);
                return mb_convert_encoding($d, "UTF-8", "UTF-16BE");
            }, $string);
        return $string;
    }
    
    $string = '\uD869\uDED6';
    echo unescape_utf16($string);
    

    在 UTF-8 中给出字符 ?(需要 4 个字节,因为它在 BMP 之外)。

    如果你所有的文本都是 UTF-16(包括 HTML 标签等),你可以简单地告诉浏览器输出是 UTF-16:

    header("Content-type: text/html; charset=UTF-16");
    

    这种情况非常少见,因为 PHP 脚本不能用 UTF-16 编写(除非 PHP 编译时支持多字节),这会使打印文字字符串很尴尬。

    因此,您可能只有一段 UTF-16 文本,您希望将其转换为您的网页使用的任何编码。您可以使用以下方法进行此转换:

    //replace UTF-8 with your actual page encoding
    mb_convert_encoding($string, "UTF-8", "UTF-16");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 2010-12-24
      • 2012-02-23
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多