简体   繁体   English

计算推文长度,例如 twitter 和 PHP

[英]Count tweet length like twitter with PHP

I want to count tweet length like twitter, I try using mb_strlen and strlen all these type here我想计算像 twitter 这样的推文长度,我在这里尝试使用mb_strlenstrlen所有这些类型

The problem is twitter count "✌️ @mention" as 15 , But I get these result and I don't know how twitter count emoji and how to approach this with php问题是 twitter 将"✌️ @mention" 15 ,但我得到了这些结果,但我不知道 twitter 如何计算表情符号以及如何使用 php 来解决这个问题

My result:我的结果:

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

From Twitter's developer documentation :来自Twitter 的开发者文档

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.对于在 Unicode 处理方面有经验的程序员来说,这个问题的简短答案是推文长度是通过文本的 NFC 规范化版本中的代码点数来衡量的。

So to calculate the length of a tweet in PHP, you would first normalize the text using Normalization Form C (NFC) and then count the number of codepoints ( NOT CHARACTERS ) in the normalized 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

@Sherif Answer is not working in some cases. @Sherif Answer 在某些情况下不起作用。 I found this library that work perfectly nojimage/twitter-text-php我发现这个库可以完美nojimage/twitter-text-php

here is my code这是我的代码

use Twitter\Text\Parser;

$validator = Parser::create()->parseTweet($caption);
        
if ($validator->weightedLength > 280) {
    throw new MessageException("Maximum post length is 280 characters.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM