当前位置: 移动技术网 > IT编程>开发语言>PHP > 让CodeIgniter的ellipsize()支持中文截断的方法

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

2019年03月24日  | 移动技术网IT编程  | 我要评论

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,这样就能很好的支持中文截断了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网