在文章摘要、搜索結果片段、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..."
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) 切換策略。intl 擴展 IntlBreakIterator::createWordInstance())。grapheme_str_split() (PHP 8.4+) 或 IntlBreakIterator::createCharacterInstance() 正確計數。symfony/string 的 AbstractUnicodeString::truncate(),內建 Unicode 感知、HTML 感知、單詞/字符/字節三模式。voku/portable-utf8 的 UTF8::words_limit()。text-overflow: ellipsis; -webkit-line-clamp: 3; 實現純視覺截斷,無需後端處理(SEO 需真實摘要時除外)。單詞級截取看似簡單,實則涉及 Unicode 分詞、HTML 結構保持、多語言策略,建議直接使用成熟庫而非手寫正則。