当前位置:首页 > CMS教程 > 其它CMS > 列表

让CodeIgniter的ellipsize()支持中文截断的方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-02-18 15:28:46 浏览: 评论:0 

CodeIgniter的Text Helper有一个ellipsize()方法,用来过滤HTML标签并且截断文字十分好用。但是它对中文支持的特别不好,在中文中使用就有乱码出现。这篇文章主要介绍了让CodeIgniter的ellipsize()支持中文截断的方法,需要的朋友可以参考下。

CodeIgniter的Text Helper有一个ellipsize()方法,用来过滤HTML标签并且截断文字十分好用。但是它对中文支持的特别不好,在中文中使用就有乱码出现。

下面有网友将function ellipsize()进行了修改,使得它支持中文:

在CI 2.1.3版本中,修改ci_2.1.3\system\helpers\text_helper.php 文件,代码如下:

  1. function ellipsize($codepage = 'UTF-8', 
  2.                    $str, $max_length, $position = 1, $ellipsis = '…') 
  3. { 
  4.     // Strip tags 
  5.     $str = trim(strip_tags($str)); 
  6.  
  7.     // Is the string long enough to ellipsize? 
  8.     if (mb_strlen($str, $codepage) <= $max_length) 
  9.     { 
  10.         return $str; 
  11.     } 
  12.  
  13.     $beg = mb_substr($str, 0, floor($max_length * $position), $codepage); 
  14.  
  15.     $position = ($position > 1) ? 1 : $position; 
  16.  
  17.     if ($position === 1) 
  18.     { 
  19.         $end = mb_substr($str, 0, 
  20.             -($max_length - mb_strlen($beg, $codepage)), $codepage); 
  21.     } 
  22.     else 
  23.     { 
  24.         $end = mb_substr($str, 
  25.             -($max_length - mb_strlen($beg, $codepage)), $max_length, $codepage); 
  26.     } 
  27.  
  28.     return $beg.$ellipsis.$end; 
  29. } 

这段代码主要将substr和strlen替换成了mb_substr和mb_strlen,这样就能很好的支持中文截断了。

Tags: CodeIgniter ellipsize

分享到: