Thinkphp program code for intercepting Chinese Strings

Source: Internet
Author: User

Add the following code to the Common directory in the project directory. php files, such as www/Common/common. php file, of course, you can also directly add it to the Common/common of thinkphp. in the php file, all projects can be used.

The code is as follows: Copy code

Function truncate_cn ($ string, $ length = 0, $ ellipsis = '... ', $ Start = 0 ){
$ String = strip_tags ($ string );
$ String = preg_replace ('/\ n/is', '', $ string );
// $ String = preg_replace ('/|/is', ', $ string); // clear spaces in the string
$ String = preg_replace ('/& nbsp;/is', '', $ string );
Preg_match_all ("/[\ x01-\ x7f] | [\ xc2-\ xdf] [\ x80-\ xbf] | \ xe0 [\ xa0-\ xbf] [\ x80- \ xbf] | [\ xe1-\ xef] [\ x80-\ xbf] [\ x80-\ xbf] | \ xf0 [\ x90-\ xbf] [\ x80 -\ xbf] [\ x80-\ xbf] | [\ xf1-\ xf7] [\ x80-\ xbf] [\ x80-\ xbf] [\ x80-\ xbf]/", $ string, $ string );
If (is_array ($ string )&&! Empty ($ string [0]) {
$ String = implode ('', $ string [0]);
If (strlen ($ string) <$ start + 1 ){
Return '';
  }
Preg_match_all ("/./su", $ string, $ ar );
$ String2 = '';
$ Tstr = '';
// Www.111cn.net
For ($ I = 0; isset ($ ar [0] [$ I]); $ I ++ ){
If (strlen ($ tstr) <$ start ){
$ Tstr. = $ ar [0] [$ I];
} Else {
If (strlen ($ string2) <$ length + strlen ($ ar [0] [$ I]) {
$ String2. = $ ar [0] [$ I];
} Else {
Break;
    }
   }
  }
Return $ string = $ string2? $ String2: $ string2. $ ellipsis;
} Else {
$ String = '';
 }
Return $ string;
}

The thinkphp template is used as follows:

The code is as follows: Copy code

{$ Info. subject | truncate_cn = 40, '', 0}

It means to intercept the $ info ['subobject'] string. The string with a length of 40 is truncated starting from 0th. If the length of the truncated string is smaller than the length of the original string, nothing is displayed, the default value is... in fact, the following two parameters are optional.

 

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.