程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> 讓CodeIgniter的ellipsize()支持中文截斷的方法

讓CodeIgniter的ellipsize()支持中文截斷的方法

編輯:PHP綜合

CodeIgniter的Text Helper有一個ellipsize()方法,用來過濾HTML標簽並且截斷文字十分好用。但是它對中文支持的特別不好,在中文中使用就有亂碼出現。

下面有網友將function ellipsize()進行了修改,使得它支持中文:

在CI 2.1.3版本中,修改ci_2.1.3\system\helpers\text_helper.php 文件

復制代碼 代碼如下: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,這樣就能很好的支持中文截斷了。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved