php - UCS2/HexEncoded 字符到 UTF8 在 php

标签 php utf-8 ucs2

我之前问过一个从 UTF-8 获取 UCS-2/HexEncoded 字符串的问题,我在以下链接中得到了一些人的帮助。

UCS2/HexEncoded characters

但现在我需要从 PHP 中的 UCS-2/HexEncoded 字符串中获取正确的 UTF-8。

对于以下字符串:

00480065006C006C006F 将返回 'Hello'

06450631062d0628064b06270020063906270644064500200021 将以阿拉伯语返回 (!مرحبا عالم)

最佳答案

您可以通过使用 hexdec() 转换十六进制字符,重新打包组件字符,然后使用 mb_convert_encoding() 将 UCS- 2 转换为 UTF-8。正如我在回答您的其他问题时提到的,您仍然需要注意输出编码,尽管您在这里特别要求使用 UTF-8,因此我们将在接下来的示例中使用它。

这是一个示例,它执行将十六进制的 UCS-2 转换为原生字符串形式的 UTF-8 的工作。由于 PHP 当前不附带 hex2bin() 函数,这会使事情变得非常简单,我们将使用最后的引用链接中发布的函数。我已将它重命名为 local_hex2bin() 以防它与 PHP 的 future 版本或您包含在项目中的其他一些第 3 方代码中的定义发生冲突。

<?php
function local_hex2bin($h)
{
if (!is_string($h)) return null;
$r='';
for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
return $r;
};

header('Content-Type: text/html; charset=UTF-8');
mb_http_output('UTF-8');
echo '<html><head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
echo '</head><body>';
echo 'output encoding: '.mb_http_output().'<br />';
$querystring = $_SERVER['QUERY_STRING'];
// NOTE: we could substitute one of the following:
// $querystring = '06450631062d0628064b06270020063906270644064500200021';
// $querystring = '00480065006C006C006F';
$ucs2string = local_hex2bin($querystring);
// NOTE: The source encoding could also be UTF-16 here.
// TODO: Should check byte-order-mark, if available, in case
//       16-bit-aligned bytes are reversed.
$utf8string = mb_convert_encoding($ucs2string, 'UTF-8', 'UCS-2');
echo 'query string: '.$querystring.'<br />';
echo 'converted string: '.$utf8string.'<br />';
echo '</body>';
?>

在本地,我调用了这个示例页面 UCS2HexToUTF8.php,然后使用查询字符串来设置输出。

UCS2HexToUTF8.php?06450631062d0628064b06270020063906270644064500200021
--
encoding: UTF-8
query string: 06450631062d0628064b06270020063906270644064500200021
converted string: مرحبًا عالم !

UCS2HexToUTF8.php?00480065006C006C006F
--
output encoding: UTF-8
query string: 00480065006C006C006F
converted string: Hello

这是 hex2bin() 函数原始来源的链接。
PHP: bin2hex(), comment #86123 @ php.net

此外,正如我在调用 mb_convert_encoding() 之前的评论中所述,您可能想要尝试检测源正在使用哪种字节顺序,尤其是当您的应用程序包含部分一台服务器上的一个或多个 CPU 在方向上与其他 CPU 不同。

这是一个可以帮助您识别字节顺序标记 (BOM) 的链接。
Byte order mark @ Wikipedia

关于php - UCS2/HexEncoded 字符到 UTF8 在 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005358/

相关文章:

php - 尝试上传大型 sql 文件时收到错误消息 : import. php:缺少参数:import_type

从项目安装 Composer 时出现 Php fatal error

python - 在 Python ftplib 中列出名称中包含 UTF-8 字符的文件

c++ - 使用 std::codecvt_xxx 将 C++ std::wstring 转换为 utf8

php - 在 PHP 中使用准备好的语句插入/显示多个带有外键的 MySQL 表

php - 通过 URL 显示 PHP 图像

c++ - 如何将文本从 CP437 编码转换为 UTF8 编码?

gsm - USSD 消息中的最大字符数是多少?

sql-server - 将 C# 字符串 (UTF-16) 存储在 SQL Server nvarchar (UCS-2) 列中会产生什么后果?

sql-server - 如何将 UTF-8 数据从经典 asp 表单发布转换为 UCS-2 以插入 SQL Server 2008 r2?