2 回答
TA貢獻1818條經驗 獲得超8個贊
來自 Twitter 的開發者文檔:
對于具有Unicode處理經驗的程序員來說,這個問題的簡短答案是,推文長度是通過文本的NFC規范化版本中的碼位數來衡量的。
因此,要計算PHP中推文的長度,您將首先使用規范化表單C(NFC)規范化文本,然后計算規范化文本中的碼位(不是字符)的數量。
$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
TA貢獻1798條經驗 獲得超7個贊
在某些情況下,@Sherif答案不起作用。我發現這個庫運行良好nojimage/twitter-text-php
這是我的代碼
use Twitter\Text\Parser;
$validator = Parser::create()->parseTweet($caption);
if ($validator->weightedLength > 280) {
throw new MessageException("Maximum post length is 280 characters.");
}
- 2 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
