You need to enable JavaScript to run this app. PHP适配Telegram偏移量处理json_decode后含emoji文本的字符串截取问题
优惠活动
大模型
产品
解决方案
定价
更多

PHP适配Telegram偏移量处理json_decode后含emoji文本的字符串截取问题

适配Telegram UTF-16码元偏移规则的字符串截取实现

核心场景

  • 待处理的字符串由JSON解码得到:原JSON字符串为"\ud83e\uddea test",经json_decode()解码后内容为🧪 test
  • 外部传入的截取参数来自Telegram消息实体接口,计数规则为UTF-16 16位码元计数:即每个UTF-16码元为1个计数单元,对于U+10000以上的Unicode字符(如测试用的🧪),因为会被编码为2个连续UTF-16代理码元,因此会被计为2个位置。对应计数位置为:

    <offset 0>\ud83e<offset 1>\uddea<offset 2> <offset 3>test

  • 传入参数offset = 3、length = 4时,目标截取结果为单词test

常规内置函数的适配偏差

PHP内置的字符串截取函数的计数规则和Telegram要求不匹配,测试代码及运行结果如下:

$input = '🧪 test';

$encoded = json_encode($input); // 输出值为 "\ud83e\uddea test"
$decoded = json_decode($encoded);

$substr = substr($decoded, 3, 4);
$mb_substr = mb_substr($decoded, 3, 4);
$iconv_substr = iconv_substr($decoded, 3, 4);

var_dump(compact(
    'encoded', 
    'decoded', 
    'substr',       // 输出 "� te",按原始字节计数,结果错误
    'mb_substr',    // 输出 "est",按Unicode码点计数,结果错误
    'iconv_substr'  // 输出 "est",按Unicode码点计数,结果错误
));

偏差原因很明确:🧪在Unicode码点层面是单个字符,按码点计数时字符串的位置为<offset 0>🧪<offset 1> <offset 2>test,因此按offset=3截取自然得到错位的结果est。

现有临时方案的缺陷

当前常用的临时绕过实现为指定BIG-5编码配合mb_substr完成截取:

$input = '🧪 test';
var_dump(mb_substr($input, 3, 4, 'BIG-5')); // 输出 "test"

该方案本质是因为BIG-5编码无法正确识别UTF-8序列的字符边界,会把连续的UTF-8字节按双字节规则拆分,仅能在当前测试用例下刚好匹配位置。遇到非BIG-5兼容字符、不同长度的UTF-8编码序列时,会出现计数完全错位的问题,不具备生产环境的可靠性。

生产可用的准确实现

核心逻辑是将字符串转换为UTF-16编码后,按16位码元为单位完成计数截取,再转回UTF-8输出,完全对齐Telegram接口的计数规则:

/**
 * 适配Telegram UTF-16码元偏移规则的字符串截取方法
 * @param string $text 待处理的UTF-8编码文本
 * @param int $offset Telegram接口传入的UTF-16码元偏移量
 * @param int|null $length Telegram接口传入的UTF-16码元截取长度
 * @return string 截取得到的UTF-8编码结果
 */
function telegramSubstr(string $text, int $offset, ?int $length = null): string
{
    // 将UTF-8文本转为UTF-16LE编码,每个16位码元固定占用2字节
    $utf16Content = mb_convert_encoding($text, 'UTF-16LE', 'UTF-8');
    // 用ISO-8859-1编码做字节映射,把连续2字节的16位码元转成可按单字节处理的字符串
    $unitMappedContent = mb_convert_encoding($utf16Content, 'ISO-8859-1', 'UTF-16LE');

    // 换算为字节级的偏移与长度(每1个UTF-16码元对应2个字节)
    $byteOffset = $offset * 2;
    $byteLength = $length !== null ? $length * 2 : null;

    // 完成截取后逐层转回UTF-8编码
    $slicedMapped = substr($unitMappedContent, $byteOffset, $byteLength);
    $slicedUtf16 = mb_convert_encoding($slicedMapped, 'UTF-16LE', 'ISO-8859-1');
    return mb_convert_encoding($slicedUtf16, 'UTF-8', 'UTF-16LE');
}

效果验证

$input = '🧪 test';
var_dump(telegramSubstr($input, 3, 4)); // 输出 "test",完全匹配预期结果

内容的提问来源于stack exchange,提问作者David Rodrigues

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 02:45:04