Home  >  Article  >  Backend Development  >  How to make CodeIgniter's ellipsize() support Chinese truncation_PHP tutorial

How to make CodeIgniter's ellipsize() support Chinese truncation_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:28:33875browse

CodeIgniter's Text Helper has an ellipsize() method, which is very useful for filtering HTML tags and truncating text. However, it does not support Chinese very well, and garbled characters appear when used in Chinese.

Some netizens below have modified function ellipsize() so that it supports Chinese:

In CI 2.1.3 version, modify the ci_2.1.3systemhelperstext_helper.php file

Copy code The code is as follows:
function ellipsize($codepage = 'UTF-8',
                                                                                                 $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;
}

This code mainly replaces substr and strlen with mb_substr and mb_strlen, so that it can support Chinese truncation well.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/788606.htmlTechArticleCodeIgniter’s Text Helper has an ellipsize() method, which is very useful for filtering HTML tags and truncating text. But it doesn’t support Chinese very well. When used in Chinese, garbled characters appear...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn