萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 按單詞數截取字符串:保持單詞完整性、支援多語言、HTML 感知截斷

在文章摘要、搜索結果片段、Meta Description 生成等場景,需按「單詞數」而非字符數截取,避免單詞被拆分。本文提供一個簡潔的 limit_words() 函數,並擴展支援 HTML 內容安全截斷(保留標籤結構)。

基礎版:純文本按空格分詞

function limit_words(string $text, int $limit, string $suffix = '...'): string {
    if ($limit <= 0) return '';
    $words = preg_split('/\s+/', $text, -1, PREG_SPLIT_NO_EMPTY);
    if (count($words) <= $limit) return $text;
    return implode(' ', array_slice($words, 0, $limit)) . $suffix;
}

// 測試
$content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed do eiusmod tempor.";
echo limit_words($content, 10); // "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed..."

進階版:HTML 內容感知截斷(保留標籤完整性)

function limit_words_html(string $html, int $limit, string $suffix = '...'): string {
    if ($limit <= 0) return '';
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML('' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    $textNodes = iterator_to_array($xpath->query('//text()'));
    $count = 0;
    $cutNode = null;
    $cutOffset = 0;

    foreach ($textNodes as $node) {
        $words = preg_split('/\s+/u', $node->nodeValue, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
        foreach ($words as [$word, $offset]) {
            if (++$count > $limit) {
                $cutNode = $node;
                $cutOffset = $offset;
                break 2;
            }
        }
    }

    if (!$cutNode) return $html; // 未超限

    // 截斷文本節點
    $cutNode->nodeValue = substr($cutNode->nodeValue, 0, $cutOffset) . $suffix;
    // 移除後續所有節點
    $next = $cutNode->nextSibling;
    while ($next) {
        $toRemove = $next;
        $next = $next->nextSibling;
        $toRemove->parentNode->removeChild($toRemove);
    }
    // 同時移除祖先鏈上後續的兄弟節點
    $ancestor = $cutNode->parentNode;
    while ($ancestor && $ancestor !== $dom) {
        $next = $ancestor->nextSibling;
        while ($next) {
            $toRemove = $next;
            $next = $next->nextSibling;
            $toRemove->parentNode->removeChild($toRemove);
        }
        $ancestor = $ancestor->parentNode;
    }

    return $dom->saveHTML();
}

多語言分詞注意事項

  • 中文/日文/韓文:無空格分隔,按字符數截取更合理。可檢測腳本 preg_match('/\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}/u', $text) 切換策略。
  • 泰文/高棉文:無空格但有單詞邊界,需 ICU 斷詞器(intl 擴展 IntlBreakIterator::createWordInstance())。
  • Emoji/組合字符:grapheme_str_split() (PHP 8.4+) 或 IntlBreakIterator::createCharacterInstance() 正確計數。

生產建議

  1. 引入 symfony/string 的 AbstractUnicodeString::truncate(),內建 Unicode 感知、HTML 感知、單詞/字符/字節三模式。
  2. 或使用 voku/portable-utf8 的 UTF8::words_limit()。
  3. 前端 CSS text-overflow: ellipsis; -webkit-line-clamp: 3; 實現純視覺截斷,無需後端處理(SEO 需真實摘要時除外)。

單詞級截取看似簡單,實則涉及 Unicode 分詞、HTML 結構保持、多語言策略,建議直接使用成熟庫而非手寫正則。

copyright © 萬盛學電腦網 all rights reserved