如何在PHP中将UTF16代理对转换为等效的HEX代码点?

时间:2016-08-30 11:43:04

标签: php utf-16 codepoint

我正在制作一个应用程序,当从iOS应用程序发送聊天时,管理员可以从使用PHP构建的管理面板查看聊天。

从DB,我将收到这样的聊天消息:

Hi, Jax\ud83d\ude1b\ud83d\ude44! can we go for a coffee?

我正在使用twemoji library,它可以将HEX代码点转换为图像。

让我们详细说一下,

在php部分,我有以下代码: -

$text = "This is fun \u1f602! \u1f1e8 ";
$html = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $text);
echo $html;

现在,twemoji解析HTML文档的整体,将Hex代码点替换为图像。

window.onload = function() {

  // Set the size of the rendered Emojis
  // This can be set to 16x16, 36x36, or 72x72
  twemoji.size = '16x16';

  // Parse the document body and
  // insert <img> tags in place of Unicode Emojis
  twemoji.parse(document.body);
}

所以,我需要将文本替换为所有UTF-16到HEX代码点(对于emojis)。 我该怎么做?

1 个答案:

答案 0 :(得分:0)

这里有一个双重问题:

  • 检测到编码的代理对
  • 实际上将该代理对转换为HTML实体

解释问题的复杂性远远超出单一答案的范围(你必须阅读UTF-16),但这段代码片段似乎解决了你的问题:

$text = "Hi, Jax\\ud83d\\ude1b\\ud83d\\ude44! can we go for a coffee?";

$result = preg_replace_callback('/\\\\u(d[89ab][0-9a-f]{2})\\\\u(d[c-f][0-9a-f]{2})/i', function ($matches) {
    $first = $matches[1];
    $second = $matches[2];
    $value = ((eval("return 0x$first;") & 0x3ff) << 10) | (eval("return 0x$second;") & 0x3ff);
    $value += 0x10000;
    return "&#$value;";
  }, $text);

echo $result;

我知道几乎总是不鼓励使用eval,但由于正则表达式匹配(您知道匹配只包含十六进制数字),因此在此示例中完全安全。

相关问题