电报机器人消息(或键盘)中的 unicode 字符(如表情符号)

unicode characters (like emoticons) in telegram bot message (or keyboard)

我正在玩 Telegram 机器人开发。 我唯一没有成功的是发送 unicode 字符。

我调用 "sendMessage" api 的方式是在 php 中使用 curl:

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array("chat_id" => $chat_id, "text" => "\u2b50"));

上面的代码应该 post 聊天中的星形图标,而不是显示确切的文本:

\u2b50

提前致谢

编辑: 用 bobince 的解决方案解决了(谢谢!)。

使用内联函数,如:

$text = preg_replace_callback('/\\u([0-9a-fA-F]{4})/', function ($match) {
    return iconv('UCS-4LE', 'UTF-8', pack('V', hexdec($match[1])));
}, $text);

$text = preg_replace("/\\u([0-9a-fA-F]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U')))", $text);

将字符集设置为 unicode...

$headers = array(
           "Content-Type: application/x-www-form-urlencoded; charset: UTF-8"
        );
curl_setopt($ch, CURLOPT_POST, $headers );
curl_setopt($ch, CURLOPT_HEADER, array("chat_id" => $chat_id, "text" => "\u2b50"));

"\u2b50"

PHP string literal 语法没有 \u 转义,主要是因为 PHP 字符串不是基于 Unicode 的,它们只是一个字节列表。

因此,如果您想在字符串中包含非 ASCII 字符,则需要使用输出的消费者期望的任何编码将该字符编码为字节。

如果 Telegram 网络服务期望接收 UTF-8(我不知道是否是,但这对任何现代网络应用程序来说都是一个很好的猜测),那么 UTF-8 编码的字节+2B50 是 0xE2、0xAD 和 0x90,因此您应该使用的字符串文字是:

"\xE2\xAD\x90"

如果您想更普遍地将 Unicode 代码点转换为 UTF-8 字符串:

function unichr($i) {
    return iconv('UCS-4LE', 'UTF-8', pack('V', $i));
}

unichr(0x2B50)   // "\xE2\xAD\x90"