In the project development, we often encounter the problem of string interception in English and Chinese, for example, the News list page needs the news content introduction, this will use the string interception.
In the project development, we often encounter the problem of string interception in English and Chinese, for example, the News list page needs the news content introduction, this will use the string interception.
Let's share a string intercept function that is already ready in thinkphp.
# function Explanation: Msubstr ($str, $start =0, $length, $charset = "Utf-8″, $suffix =true)/* $STR: String to intercept $start=0: Start position, default starting from 0 $ Length: Truncated $charset= "Utf-8″: Character encoding, default utf-8$suffix=true: Whether the ellipsis is displayed after the truncated character, the default true is displayed, False is not displayed */
Template use:
{$vo. title|msubstr=0,5, ' Utf-8 ', false}
Ps: If the core version of the function may not exist, do not be afraid, wind code to everyone to paste it out:
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;}