During project development, we often encounter string truncation problems such as English and Chinese characters. for example, on the news list page, we need to describe the news content, which requires string truncation. During project development, we often encounter string truncation problems such as English and Chinese characters. for example, on the news list page, we need to describe the news content, which requires string truncation.
During project development, we often encounter string truncation problems such as English and Chinese characters. for example, on the news list page, we need to describe the news content, which requires string truncation.
The following is a string truncation function prepared in THINKPHP.
# Function explanation: msubstr ($ str, $ start = 0, $ length, $ charset = "UTF-8", $ suffix = true)/* $ str: string to be truncated $ start = 0: start position, default start from 0 $ length: capture length $ charset = "UTF-8": Character encoding, default UTF-8 $ suffix = true: whether the ellipsis is displayed after the truncated characters. the default value is true, and the false value is false */
Template usage:
{$vo.title|msubstr=0,5,'utf-8',false}
Ps: If the function does not exist in the core version, don't worry. stick the code to everyone one by one:
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) { if(function_exists("mb_substr")){ if($suffix) return mb_substr($str, $start, $length, $charset)."..."; else return mb_substr($str, $start, $length, $charset); } elseif(function_exists('iconv_substr')) { if($suffix) return iconv_substr($str,$start,$length,$charset)."..."; else return iconv_substr($str,$start,$length,$charset); } $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/"; $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/"; $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/"; $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("",array_slice($match[0], $start, $length)); if($suffix) return $slice."…"; return $slice;}
The above is a detailed description of THINKPHP's sample code for intercepting a Chinese string function. For more information, see other related articles in the first PHP community!