PHP instance-string segmentation (perfect support for both Chinese and English, compatible with mb_substr)

Source: Internet
Author: User
/**
+ ----------------------------------------------------------
* String truncation, supporting Chinese and other Encoding
+ ----------------------------------------------------------
* @ Static
* @ Access public
+ ----------------------------------------------------------
* @ Param string $ STR string to be converted
* @ Param string $ start position
* @ Param string $ length truncation Length
* @ Param string $ charset encoding format
* @ Param string $ suffix truncated display characters
+ ----------------------------------------------------------
* @ Return string
+ ----------------------------------------------------------
*/
FunctionMsubstr ($ Str,$ Start,$ Length,$ Charset= "UTF-8 ",$ Suffix=True)
{
If(Function_exists("Mb_substr ")){
$ Slice= Mb_substr ($ Str,$ Start,$ Length,$ Charset);
}Elseif(Function_exists('Iconv _ substr ')){
$ Slice=Iconv_substr($ Str,$ Start,$ Length,$ Charset);
If(False===$ Slice){
$ Slice= '';
}
}Else{
$ 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));
}
Return $ Suffix?$ Slice.'...':$ 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.