PHP 将 utf-16 转换为 ascii

PHP converting utf-16 to ascii

我正在尝试转换一些编码文本以在网站上显示;具体示例是将字符串 "d83edd2a" 转换为表情符号。

显然编码是 UTF-16,但 php 将其检测为 ASCII。

我试过使用 hex2bin,但是 returns "Ø>Ý*" 和 php 将其检测为 UTF-8,这对我来说很有意义。

我试过几次不同的尝试

$newCode = mb_convert_encoding($code, "ASCII", "UTF-16");

但是这个returns“????”

$newCode = iconv(mb_detect_encoding($code), 'ASCII', $hex);

但这也returns“????”

我确定我遗漏了一些简单的东西,但我最终陷入了困境!

如果我没理解错的话,你想将字符串 d83edd2a 转换为相应的表情符号。

最直接的方法就是:

echo hex2bin('d83edd2a');

然而,这假定客户端使用 UTF-16 字符集。

如果客户端使用不同的字符集,你需要先转换它,否则你只会看到垃圾。

但是您不能只使用 any 编码(如 ASCII),因为表情符号是 unicode 特定的。

(ASCII 根本就没有 "know" 表情符号的概念。)

您需要使用 UTF-8、UTF-16 或 UTF-32。

既然您提到了您想要的网站 "UTF-8",它就是现代网站事实上的标准字符集。

您可以像这样从 UTF-16 转换为 UTF-8:

// First convert the string to binary data
// We know this is encoded in UTF-16
$UTF16Str = hex2bin('d83edd2a');
// Then we convert from UTF-16 to something more common like UTF-8
$UTF8Str  = mb_convert_encoding($UTF16Str, 'UTF-8', 'UTF-16');

echo $UTF8Str;

作为最后一步,请确保将字符集传达给客户端(您可以在 HTML 或 PHP 中执行此操作):

<meta charset="UTF-8"> <!-- inside <head> -->

或在PHP:

header('Content-Type: text/html; charset=UTF-8');