CodeIgniter 的 Text Helper 裡有一個 function ellipsize(),用來截斷過長的文字,同時可以指定顯示長度、截斷位置,功能上相當不錯。
殘念的是這支 function 並不支援雙位元文字或其他特殊編碼的文字,拿中文字去切非常容易出現亂碼。所以決定幫這支程式做點小小的修改,讓它可以指定編碼,拿來截斷中文也沒問題。
function ellipsize($codepage = 'UTF-8',
$str, $max_length, $position = 1, $ellipsis = '…')
{
// Strip tags
$str = trim(strip_tags($str));
// Is the string long enough to ellipsize?
if (mb_strlen($str, $codepage) <= $max_length)
{
return $str;
}
$beg = mb_substr($str, 0, floor($max_length * $position), $codepage);
$position = ($position > 1) ? 1 : $position;
if ($position === 1)
{
$end = mb_substr($str, 0,
-($max_length - mb_strlen($beg, $codepage)), $codepage);
}
else
{
$end = mb_substr($str,
-($max_length - mb_strlen($beg, $codepage)), $max_length, $codepage);
}
return $beg.$ellipsis.$end;
}
主要的修改是將 substr 與 strlen 換成 mb_substr 與 mb_strlen,然後加上編碼參數,並不是很複雜的修改。不過往後碰到需要截斷過長文字的程式都可以拿這支來用,實性用很高。
Leave a Reply