Php solves the problem of garbled characters intercepted by substr,
In php, if I want to use substr () to intercept strings in full English, it would be a tragedy if it includes Chinese or English, however, we can use other methods to solve this problem.
Php intercepts Chinese strings and garbled characters. This was recently discovered. I have previously written an article about Automatic Generation of meta information, this article describes how many words are used as the description method before intercepting articles using php, but IE6 cannot load CSS. Here is a supplement.
First of all, we need to clarify this problem. The reason why IE6 occasionally fails to load CSS is that the file is garbled and the link for loading CSS later cannot be correctly parsed by ie6. Therefore, we can see a pure HTML page, without CSS, naked! If the problem is identified, the remaining problem can be solved, that is, to prevent garbled code. Since the function provided by hichina has garbled code, a php function is found again to solve the garbled code problem.
The substr () function can split text, but if the text to be split contains Chinese characters, it will often encounter problems.
The usage of the function mb_substr () is similar to that of substr (), but an additional parameter must be added at the end to set the encoding of the string.
Here we should understand the reasons for improving the hichina method ~~
Next we will introduce several more advanced solutions.
Example 1
The Code is as follows:
Function func_chgtitle ($ str, $ len) {// $ length the maximum length of the string that we allow to display $ tmpstr = ""; $ strlen = $ 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 ;}
Example 2
Character string encoded as UTF-8, a Chinese character occupies three Bytes:
Public static function chinesesubstr ($ str, $ start, $ len) {// $ str indicates the string, $ start indicates the start position of the string, and $ len indicates the string length.
$ Strlen = $ start + $ len;// Use $ strlen to store the total length of the string, that is, from the starting position of the string to the total length of the string
The Code is as follows:
For ($ I = $ start; $ I <$ strlen;) {if (ord (substr ($ str, $ I, 1)> 0xa0) {// if the value of the first byte in the string is greater than 0xa0, it indicates the Chinese character $ tmpstr. = substr ($ str, $ I, 3); // each time a three-character string is taken out and assigned to the variable $ tmpstr, that is, a Chinese character $ I = $ I + 3; // variable auto-increment 3} else {$ tmpstr. = substr ($ str, $ I, 1); // if it is not a Chinese character, a character is taken out each time and assigned to the variable $ tmpstr $ I ++;} return $ tmpstr; // return string}
This article is intended to help you solve the same problem in PHP programming!