This article mainly introduces the php custom method for intercepting Chinese strings, which has good reference value. let's take a look at the following below: There are a lot of code for this problem on the Internet, however, many of them are copy and paste, but they do not have their own practices, 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 ;}
For more articles about customizing and intercepting a Chinese string in php-utf8, refer to the PHP Chinese website!
Related articles:
A small function that inserts a string at a specified position.
PHP development skills (10)-implementation of Chinese character string truncation without garbled characters
Code explanation of string format calculation formula using eval in php