我之前提出了一个问题,想要从UTF-8获得一个UCS-2/HexEncoded字符串,我在以下链接中得到了一些人的帮助。
但现在我需要在PHP中从一个UCS-2/HexEncoded字符串中获取正确的UTF-8。
对于以下字符串:
00480065006C006C006F 将返回 'Hello'
06450631062d0628064b06270020063906270644064500200021 将以阿拉伯语返回 (!مرحبا عالم)
我之前提出了一个问题,想要从UTF-8获得一个UCS-2/HexEncoded字符串,我在以下链接中得到了一些人的帮助。
但现在我需要在PHP中从一个UCS-2/HexEncoded字符串中获取正确的UTF-8。
对于以下字符串:
00480065006C006C006F 将返回 'Hello'
06450631062d0628064b06270020063906270644064500200021 将以阿拉伯语返回 (!مرحبا عالم)
<?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
$querystring = '06450631062d0628064b06270020063906270644064500200021';
$str = pack('H*', $querystring);
$ucs2string = mb_convert_encoding($str, 'UTF-8', 'UCS-2');
- JayUCS-2到UTF-8的更准确转换
function ucs2_to_utf8($h)
{
if (!is_string($h)) return null;
$r='';
for ($a=0; $a<strlen($h); $a+=4) { $r.=chr(hexdec($h{$a}.$h{($a+1)}.$h{($a+2)}.$h{($a+3)})); }
return $r;
}