- /**
- * 中英文字符截取函数,要求汉字字符编码必须为utf-8
- * $offset 跳过的字符个数
- * $length 截取的字符数个数
- */
- function zh_substr($str, $offset, $length = -1) {
- $ret = '';
- $bytelen = mb_strlen($str); //字符串的字节数
- $start = 0;
- $end = 0;
- $nums = 0;
- $count = 1;
- for ( $i = 0; $i < $bytelen; $i++ ) {
- if ( $nums == $offset ) {
- $start = $i;
- break;
- }
- if ( ord($str{$i}) > 0x80 || $count > 1 ) { //汉字
- if ( $count % 3 === 0 ) { //统计出一个汉字
- $nums += 1;
- $count = 1;
- } else {
- $count += 1;
- }
- continue;
- }
- $nums += 1; //统计出一个英文
- }
- $nums = 0;
- $count = 1;
- for ( $i = $start; $i < $bytelen; $i++ ) {
- if ( $nums == $length ) {
- break;
- }
- if ( ord($str{$i}) > 0x80 || $count > 1 ) { //汉字
- if ( $count % 3 === 0 ) { //统计出一个汉字
- $nums += 1;
- $count = 1;
- $end += 3;
- } else {
- $count += 1;
- }
- continue;
- }
- $nums += 1; //统计出一个英文
- $end += 1;
- }
- $ret = mb_substr($str, $start, $end);
- return $ret;
- }
- //该片段来自于http://www.codesnippet.cn/detail/190620149829.html
来源: http://www.codesnippet.cn/detail/190620149829.html