加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-12 20:14:12 所属栏目:PHP教程 来源:网络整理
导读:CodeIgniter的Text Helper有一个ellipsize()方法,用来过滤HTML标签并且截断文字十分好用。但是它对中文支持的特别不好,在中文中使用就有乱码出现。 下面有网友将function ellipsize()进行了修改,使得它支持中文: 在CI 2.1.3版本中,修改ci_2.1.3system

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

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

在CI 2.1.3版本中,修改ci_2.1.3systemhelperstext_helper.php 文件

代码如下:
$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,floor($max_length * $position),$codepage); $position = ($position > 1) ? 1 : $position; if ($position === 1)
{
$end = mb_substr($str,
-($max_length - mb_strlen($beg,$codepage)),$codepage);
}
else
{
$end = mb_substr($str,$codepage);
} return $beg.$ellipsis.$end;
}

这段代码主要将substr和strlen替换成了mb_substr和mb_strlen

,这样就能很好的支持中文截断了。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读