php - 使用 PHP 从 JSON 字符串转换 Unicode

标签 php unicode encoding utf-8 character-encoding

我一直在阅读一些解决方案,但还没有设法让任何东西发挥作用。

我有一个从 API 调用中读入的 JSON 字符串,它包含 Unicode 字符 - \u00c2\u00a3 例如是 £ 符号。

我想使用 PHP 将它们转换为 ££

我正在调查问题并发现了以下代码(使用我的井号进行测试)但它似乎没有工作:

$title = preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", '\u00c2\u00a3');

输出为 £

我认为这是 UTF-16 编码是否正确?我如何将它们转换为 HTML 输出?

更新

似乎来自 API 的 JSON 字符串有 2 或 3 个未转义的 Unicode 字符串,例如:

That\u00e2\u0080\u0099s (right single quotation)
\u00c2\u00a (pound symbol)

最佳答案

不是 UTF-16 编码。它看起来像是伪造的编码,因为\uXXXX 编码独立于 Unicode 的任何 UTF 或 UCS 编码。 \u00c2\u00a3 实际上映射到 £ 字符串。

您应该拥有的是 \u00a3,它是 £ 的 unicode 代码点。

{0xC2, 0xA3} 是此代码点的 UTF-8 编码 2 字节字符。

如果像我认为的那样,将原始 UTF-8 字符串编码为 JSON 的软件没有意识到它是 UTF-8 并盲目地将每个字节编码为转义的 unicode 代码点,那么您需要转换每一对unicode 代码指向一个 UTF-8 编码的字符,然后将其解码为 native PHP 编码以使其可打印。

function fixBadUnicode($str) {
    return utf8_decode(preg_replace("/\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})/e", 'chr(hexdec("$1")).chr(hexdec("$2"))', $str));
}

此处示例:http://phpfiddle.org/main/code/6sq-rkn

编辑:

如果要修复字符串以获得有效的JSON字符串,需要使用如下函数:

function fixBadUnicodeForJson($str) {
    $str = preg_replace("/\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})/e", 'chr(hexdec("$1")).chr(hexdec("$2")).chr(hexdec("$3")).chr(hexdec("$4"))', $str);
    $str = preg_replace("/\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})/e", 'chr(hexdec("$1")).chr(hexdec("$2")).chr(hexdec("$3"))', $str);
    $str = preg_replace("/\\\\u00([0-9a-f]{2})\\\\u00([0-9a-f]{2})/e", 'chr(hexdec("$1")).chr(hexdec("$2"))', $str);
    $str = preg_replace("/\\\\u00([0-9a-f]{2})/e", 'chr(hexdec("$1"))', $str);
    return $str;
}

编辑 2: 修复了之前的函数,将任何错误的 unicode 转义 utf-8 字节序列转换为等效的 utf-8 字符。

请注意,其中一些可能来自 Word 等编辑器的字符无法翻译为 ISO-8859-1,因此将显示为“?”在 ut8_decode 之后。

关于php - 使用 PHP 从 JSON 字符串转换 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523846/

相关文章:

java - Apache Tomcat 服务器(在 Linux 机器中)区域设置和 Unicode 字符替换为 '?'

php - Unicode字符插入数据库后变成问号

java - 哪个是最好的媒体容器?

python - FTP文件名编码

javascript - 树莓派 PHP GPIO 读取

几分钟后 PHP session 超时

php - JQuery 表单保持静态 - 页面不会动态验证

LocalHost 上的 PHP 连接被拒绝 (HY000/2002)

unicode - 包输入错误 : Unicode char\u8:β not set up for use with LaTeX

Google Drive API V3 如何正确转义查询参数?