Phpsubstr Chinese garbled solution

Source: Internet
Author: User
Phpsubstr Chinese garbled solution if substr is directly used to intercept Chinese strings, it will certainly produce garbled characters, because it will divide a Chinese character into half. why is it like this? due to internal machine encoding problems, now let's look at the solution

1. use mb_substr of the mbstring Extension Library to intercept the database without garbled characters.

2. write the truncation function by yourself, but it is not as efficient as using the mbstring Extension Library.

3. if the string is intercepted only for the output, it can be implemented as follows: substr ($ str, 0, 30). chr (0 ).

The PHP instance code is as follows:

* Chinese characters can be intercepted without garbled characters

* The parameter $ str is a string, $ start is the start character, and $ len is the end character.

* Returns the truncated characters.

*/

Function msubstr ($ str, $ start, $ len ){

$ Tmpstr = ""; // open-source phpfensi.com

$ Strlen = $ start + $ len;

For ($ I = 0; $ I <$ strlen; $ I ++ ){

If (ord (substr ($ str, $ I, 1)> 0xa0 ){

$ Tmpstr. = substr ($ str, $ I, 2 );

$ I ++;

} Else

$ Tmpstr. = substr ($ str, $ I, 1 );

}

Return $ tmpstr;

}

Method 2: php implements the method of intercepting Chinese strings without garbled characters. the code is as follows:

Function gbsubstr ($ string, $ start, $ length ){

If (strlen ($ string)> $ length ){

$ Str = null;

$ Len = $ start + $ length;

For ($ I = $ start; $ I <$ len; $ I ++ ){

If (ord (substr ($ string, $ I, 1)> 0xa0 ){

$ Str. = substr ($ string, $ I, 2 );

$ I ++;

} Else {

$ Str. = substr ($ string, $ I, 1 );

}

}

Return $ str .'...';

} Else {

Return $ string;

}

}

?>

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.