網頁常需截取子字串,truncate 只適合英文,中文會產生亂碼;中英混合截取同字數視覺長度不同,影響美觀(一中文≈兩英文長度)。且 truncate 不能同時相容 GB2312、UTF-8 編碼。
檔案名:modifier.smartTruncate.php
truncate 原有功能<?php
function smartDetectUTF8($string) { /* UTF-8 偵測 */ }
function smartStrlen($string) { /* 計算視覺長度 */ }
function smartSubstr($string, $start, $length = null) { /* 多編碼安全截取 */ }
function smarty_modifier_smartTruncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) { /* 主修飾器 */ }
?>
(完整代碼見原文,此處略去詳列)
{$content|smartTruncate:5:".."}
$content = "A中B華C人D民E共F和G國H"
顯示:A中B華C..(中文長度 1.0、英文 0.5、含省略號長度)
無論 GB2312 或 UTF-8 編碼,結果皆正確,故命名加上 smart。
希望本文對大家的 PHP 程式設計有所幫助。