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

Smarty 變數修飾器完整速查表:內建 25+ 修飾器用法、參數與自訂擴充指南

     編輯:PHP 綜合知識

語法基本形式

{$var|modifier1|modifier2:param1:param2|modifier3}
  • 管線符 `|` 串聯多個修飾器,左到右執行
  • 參數用冒號 `:` 分隔,字串參數建議加引號

25+ 內建修飾器分類速查

大小寫轉換

修飾器功能範例結果
lower全小寫{$name|lower}john
upper全大寫{$name|upper}JOHN
capitalize單字首字大寫{$title|capitalize}Hello World
capitalize:true含數字單字也大寫{$code|capitalize:true}Php7 → Php7

字串截取與長度

修飾器功能參數範例
truncate截斷並加尾碼長度, 尾碼, 斷詞{$text|truncate:30:"..."}
strip壓縮空白/換行替代字串{$text|strip:" "}
strip_tags移除 HTML 標籤允許標籤{$html|strip_tags:""}
count_characters計算字元數含空白{$str|count_characters:true}
count_words計算單字數—{$str|count_words}
count_sentences計算句子數—{$str|count_sentences}
count_paragraphs計算段落數—{$str|count_paragraphs}

字串搜尋替換

修飾器功能參數範例
replace簡單字串替換搜尋, 替換{$str|replace:"old":"new"}
regex_replace正則替換模式, 替換{$str|regex_replace:"/\d+/":"#"}

編碼與格式化

修飾器功能參數範例
escapeHTML/URL/JS/HEX 編碼html|url|javascript|hex{$var|escape:'html'}
date_format日期格式化strftime 格式, 預設時間{$time|date_format:"%Y-%m-%d"}
string_formatsprintf 格式化格式字串{$price|string_format:"%.2f"}
nl2br換行轉 <br>—{$text|nl2br}
spacify字元間插入字串插入字串{$str|spacify:"-"}
indent每行縮排字元數, 字元{$block|indent:4:"\t"}
cat尾部連接字串字串{$str|cat:" suffix"}

預設值

{$title|default:"無標題"}  {* 變數為空/未指派時顯示預設 *}

自訂修飾器開發

  1. 建立 plugins/modifier.修飾器名.php
  2. 函式命名:smarty_modifier_修飾器名($string, $param1, ...)
  3. 回傳處理後字串
// plugins/modifier.reverse.php
function smarty_modifier_reverse($string) {
    return strrev($string);
}

// 模板使用
{$text|reverse}  {* 反轉字串 *}

效能建議

  • 避免在迴圈內對大字串串聯多個複雜修飾器
  • PHP 端預處理後再 assign() 給模板
  • 編譯後模板為 PHP 程式碼,修飾器實際為函式呼叫,開銷極低

相關專題

  • 《Smarty 模板入門基礎教程》
  • 《PHP 模板技術總結》
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved