Detailed thinkphp intercept Chinese string function instance code

Source: Internet
Author: User
Tags truncated
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;} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.