|
@@ -324,8 +324,7 @@ class TwitterService implements SmmPlatformInterface
|
|
|
*/
|
|
|
public function uploadAndPost($filePaths, $tweetText) {
|
|
|
try {
|
|
|
-
|
|
|
- $tweetText = $this->truncateText($tweetText, 138);// 截断推文
|
|
|
+ $tweetText = $this->truncateText($tweetText, 270);// 截断推文
|
|
|
|
|
|
$media_ids = [];
|
|
|
foreach ($filePaths as $filePath) {
|
|
@@ -455,28 +454,37 @@ class TwitterService implements SmmPlatformInterface
|
|
|
}
|
|
|
|
|
|
|
|
|
+
|
|
|
/**
|
|
|
- * 安全截断多字节文本(支持中文、日文等)
|
|
|
+ * 安全截断多字节文本(按字符宽度计算,支持中文、日文、葡萄牙语等)
|
|
|
* @param string $text 原始文本
|
|
|
- * @param int $maxLength 最大长度(默认280)
|
|
|
+ * @param int $maxWidth 最大显示宽度(默认 280)
|
|
|
* @param string $ellipsis 截断后缀(默认...)
|
|
|
* @return string 处理后的文本
|
|
|
*/
|
|
|
- function truncateText(string $text, int $maxLength = 140, string $ellipsis = ''): string {
|
|
|
- // 检测文本长度
|
|
|
- $textLength = mb_strlen($text, 'UTF-8');
|
|
|
+ function truncateText(string $text, int $maxWidth = 270, string $ellipsis = ''): string {
|
|
|
+ if ($maxWidth <= 0) return '';
|
|
|
+
|
|
|
+ // 计算后缀的显示宽度
|
|
|
+ $ellipsisWidth = mb_strwidth($ellipsis, 'UTF-8');
|
|
|
|
|
|
- if ($textLength <= $maxLength) {
|
|
|
- return $text;
|
|
|
+ // 如果后缀宽度已超过最大限制
|
|
|
+ if ($ellipsisWidth >= $maxWidth) {
|
|
|
+ return mb_strimwidth($ellipsis, 0, $maxWidth, '', 'UTF-8');
|
|
|
}
|
|
|
|
|
|
- // 计算后缀长度
|
|
|
- $ellipsisLength = mb_strlen($ellipsis, 'UTF-8');
|
|
|
+ // 允许的文本部分最大宽度
|
|
|
+ $allowedWidth = $maxWidth - $ellipsisWidth;
|
|
|
|
|
|
- // 确保后缀不会导致总长度超过限制
|
|
|
- $truncateLength = $maxLength - $ellipsisLength;
|
|
|
+ // 直接检查完整文本宽度
|
|
|
+ $textWidth = mb_strwidth($text, 'UTF-8');
|
|
|
+ if ($textWidth <= $allowedWidth) {
|
|
|
+ return $text . $ellipsis;
|
|
|
+ }
|
|
|
|
|
|
- // 安全截取并添加后缀
|
|
|
- return mb_substr($text, 0, $truncateLength, 'UTF-8') . $ellipsis;
|
|
|
+ // 精确截断(处理最后字符可能被切断的情况)
|
|
|
+ $truncated = mb_strimwidth($text, 0, $allowedWidth, '', 'UTF-8');
|
|
|
+ return $truncated . $ellipsis;
|
|
|
}
|
|
|
+
|
|
|
}
|