首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Smart 截斷修飾器 truncate 完整用法大全

     編輯:PHP 相關知識

truncate 基本語法

{$var|truncate[:length[:etc[:break_words[:middle]]]]}
  • length:截取長度(預設 80),包含 etc 字串長度
  • etc:尾部附加字串(預設 ...)
  • break_words:true 強制在指定長度截斷(可能斷詞),false 於詞邊界截斷(預設)
  • middle:true 從中間截斷(兩端保留),false 從尾部截斷(預設)

實際範例

<?php
// index.php
$smarty = new Smarty;
$smarty->assign('articleTitle', 'Two Sisters Reunite after Eighteen Years at Checkout Counter.');
$smarty->display('index.tpl');
?>
{* index.tpl *}
{$articleTitle}
{$articleTitle|truncate}
{$articleTitle|truncate:30}
{$articleTitle|truncate:30:""}
{$articleTitle|truncate:30:"---"}
{$articleTitle|truncate:30:"":true}
{$articleTitle|truncate:30:"...":true}

輸出結果對照

範本語法輸出結果說明
{$articleTitle}Two Sisters Reunite after Eighteen Years at Checkout Counter.原文
{$articleTitle|truncate}Two Sisters Reunite after Eighteen Years at Checkout Counter.未超過 80 字,不截斷
{$articleTitle|truncate:30}Two Sisters Reunite after...詞邊界截斷 + 預設 ...
{$articleTitle|truncate:30:""}Two Sisters Reunite after無尾碼,詞邊界
{$articleTitle|truncate:30:"---"}Two Sisters Reunite after---自訂尾碼 ---
{$articleTitle|truncate:30:"":true}Two Sisters Reunite after Eigh強制 30 字截斷(斷詞)
{$articleTitle|truncate:30:"...":true}Two Sisters Reunite after E...強制截斷 + 尾碼 ...

進階技巧

  • 中文環境:預設按字元計算,中文無空格分詞,建議搭配 break_words=true 或使用 mb_truncate 自訂修飾器。
  • 中間截斷:{$longUrl|truncate:50:"...":false:true} 保留開頭網域與結尾檔名,中間用 ... 取代。
  • 搭配其他修飾器:{$text|strip_tags|truncate:100:"..."} 先移除 HTML 標籤再截斷。

常見誤區

  1. 以為 length 不含 etc 長度 —— 實際包含在內。
  2. 以為預設會在單字中間斷開 —— 實際預設尋找空格,只有加 true 才強制斷詞。
  3. 以為 truncate 支援 HTML 感知截斷 —— 不支援,會破壞標籤結構,需先 strip_tags。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved