php - 使用 PHP 计算 Twitter 等推文长度

标签 php

我想像推特一样计算推文长度,我尝试使用 mb_strlenstrlen所有这些类型 here

问题是推特计数 "👍🏿✌🏿️ @mention" 15 ,但我得到了这些结果,我不知道 Twitter 如何计算表情符号以及如何使用 php 解决这个问题

我的结果:

strlen: 27
mb_strlen UTF-8: 14
mb_strlen UTF-16: 13
iconv UTF-16: 14
iconv UTF-16: 27

最佳答案

来自 Twitter's developer documentation :

For programmers with experience in Unicode processing the short answer to the question is that Tweet length is measured by the number of codepoints in the NFC normalized version of the text.



因此,要在 PHP 中计算推文的长度,您首先要使用 对文本进行规范化。标准化表格 C (NFC) 然后计算规范化文本中的代码点数( NOT CHARACTERS )。
$text = "👍🏿✌🏿️ @mention";

// Get the normalized text in UTF-8
$NormalizedText = Normalizer::normalize($text, Normalizer::FORM_C );

// Now we can calculate the number of codepoints in this normalized text
$it = IntlBreakIterator::createCodePointInstance();
$it->setText($NormalizedText);

$len = 0;
foreach ($it as $codePoint) {
    $len++;
}

echo "Length = $len"; // Result: Length = 15

关于php - 使用 PHP 计算 Twitter 等推文长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916326/

相关文章:

php - 如果包含通知负载,GCM ios 将无法正常工作

php - PHP 核心如何处理客户端连接?

php - 需要使用 header() 函数下载文件的帮助

JavaScript PHP 引导通知

php - FreeRADIUS - session 过期时从数据库中删除用户

php - php 中没有通过表单输入数据

php - 将数据库值传递给 JavaScript

php - 列 'custID' 不能为空

javascript - 无法从 JSON 数组和对象获取值

PHP方程输出困惑