All PHP users know that strlen and mb_strlen are functions used to evaluate the string length. However, for some beginners, if they do not read the manual, they may not know the difference.
All PHP users know that strlen and mb_strlen are functions used to evaluate the string length. However, for some beginners, if they do not read the manual, they may not know the difference.
Let's take a look at this piece of code (the prerequisite is that the character encoding is UTF-8 ):
$ Str = 'All PHP users 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:
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:
$ 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 );
?>