我想像推特一样计算推文长度,我尝试使用 mb_strlen
和 strlen
所有这些类型 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/