The problem of garbled characters in the Chinese string intercepted by substr
Source: Internet
Author: User
This article is the use of substr capture UTF-8 Chinese strings appear garbled problem for a detailed analysis of the introduction, need a friend reference we know that sometimes use substr to capture UTF-8 Chinese strings, garbled characters often occur. why is such a problem? I will tell you the answer in this article.
Take a look at this piece of code (character encoding for UTF-8 ): The code is as follows:
$ Str = 'all know that strlen and mb_strlen are functions for string lengths ';
Echo strlen ($ str )'.
'. Mb_strlen ($ str, 'utf-8 ');
?>
Run the preceding code and return the following values:
66
34
How is it? In strlen, Chinese is the length of three bytes, while English is the length of one byte! The length of mb_strlen is calculated as a byte! So, we sometimes use substr to intercept the Chinese string of the UTF-8, often garbled, that is why!
The following provides a function to intercept a UTF-8 string:
The code is as follows:
Function cutstr ($ sourcestr, $ cutlength ){
$ Returnstr = '';
$ I = 0;
$ N = 0;
$ Str_length = strlen ($ sourcestr );
$ Mb_str_length = mb_strlen ($ sourcestr, 'utf-8 ');
While ($ n <$ cutlength) & ($ I <= $ str_length )){
$ Temp_str = substr ($ sourcestr, $ I, 1 );
$ Ascnum = ord ($ temp_str );
If ($ ascnum> = 224 ){
$ Returnstr = $ returnstr. substr ($ sourcestr, $ I, 3 );
$ I = $ I + 3;
$ N ++;
}
Elseif ($ ascnum & gt; = 192 ){
$ Returnstr = $ returnstr. substr ($ sourcestr, $ I, 2 );
$ I = $ I + 2;
$ N ++;
}
Elseif ($ ascnum> = 65) & ($ ascnum <= 90 )){
$ Returnstr = $ returnstr. substr ($ sourcestr, $ I, 1 );
$ I = $ I + 1;
$ N ++;
}
Else {
$ Returnstr = $ returnstr. substr ($ sourcestr, $ I, 1 );
$ I = $ I + 1;
$ N = $ n + 0.5;
}
}
If ($ mb_str_length> $ cutlength ){
$ Returnstr = $ returnstr ."...";
}
Return $ returnstr;
}
Example:
The code is as follows:
$ Str = 'validity period: up to three months. If the validity period is exceeded, the system will automatically delete this message ';
// Echo strlen ($ str );
// Echo' '. Mb_strlen ($ str, 'utf-8 ');
Echo' '. $ Str;
Echo' '. Cutstr ($ str, 24 );
?>
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