Php custom truncation of Chinese strings-utf8 version,
Note: There are a lot of code for this problem on the Internet, but many of them are copied and pasted without practice, and the code has logic problems. The following code is compiled by myself.
Not much talk
/*** This function is for utf8 encoding * @ author 2582308253@qq.com * @ param string $ str * @ param int $ start * @ param int $ length * @ return string * @ copyright February 27, 2017 1:46:10 pm */function gbsubstr2 ($ str, $ start, $ length) {$ length = abs ($ length); $ strLen = strlen ($ str); $ len = $ start + $ length; $ newStr = ''; for ($ I = $ start; $ I <$ len & $ I <$ strLen; $ I ++) {if (ord (substr ($ str, $ I, 1)> 0xa0) {// a Chinese character in UTF-8 encoding occupies three bytes. For other encoded strings, Chinese characters occupy different bytes, you need to modify the number a $ newStr. = substr ($ str, $ I, 3); // here a = 3; $ I + = 2; $ len + = 2; // after intercepting three bytes, the end offset of the truncated string also needs to increase the A-1 with each Chinese Character truncation;} else {$ newStr. = substr ($ str, $ I, 1) ;}return $ newStr ;}
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!