'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

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

My result:

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


Solution 1:[1]

@Sherif Answer is not working in some cases. I found this library that work perfectly 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.");
}

Solution 2:[2]

From 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.

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.

$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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali Akbar Azizi
Solution 2