Home > Article > Backend Development > How to intercept Chinese string (utf8) in php
This article mainly introduces the method of php custom intercepting Chinese strings, which has a very good reference value. Let’s take a look at it with the editor.
First explain: Currently on the Internet There are a lot of codes for this problem, but many of them are copied and pasted without practice by myself, and the codes have logical problems. The following codes are written by myself.
Not much to say
/** * 该函数是对于utf8编码 * @author 2582308253@qq.com * @param string $str * @param int $start * @param int $length * @return string * @copyright 2017年2月27日下午1:46:10 */ 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) { //utf8编码中一个汉字是占据3个字节的,对于其他的编码的字符串,中文占据的字节各有不同,自己需要去修改这个数a $newStr .= substr($str, $i, 3);//此处a=3; $i+=2; $len += 2; //截取了三个字节之后,截取字符串的终止偏移量也要随着每次汉字的截取增加a-1; } else { $newStr .= substr($str, $i, 1); } } return $newStr; }
The above is the detailed content of How to intercept Chinese string (utf8) in php. For more information, please follow other related articles on the PHP Chinese website!