查询utf-8的编码规范
最高字节
0xxx xxxx , 1个字节
110xx xxxx , 2个字节
1110 xxxx, 3 3个字节
1111 0xxxx 4... 4个字节
......
<?php $str = '这是一段测试代码aaaa不知道可行否b看看吧!'; /* $str 是待截取的字符串 $len 是截取的字符数 */ function utf8sub($str,$len) { if($len <= 0) { return ''; } $length = strlen($str); //待截取的字符串字节数 // 先取字符串的第一个字节,substr是按字节来的 $offset = 0; // 这是截取高位字节时的偏移量 $chars = 0; // 这是截取到的字符数 $res = ''; // 这是截取的字符串 while($chars < $len && $offset < $length) { //只要还没有截取到$len的长度,就继续进行 $high = decbin(ord(substr($str,$offset,1))); //已经能够判断高位字节 if(strlen($high) < 8) { // 截取1个字节 $count = 1; } else if(substr($high,0,3) == '110') { // 截取2个字节 $count = 2; } else if(substr($high,0,4) == '1110') { // 截取3个字节 $count = 3; } else if(substr($high,0,5) == '11110') { // 截取4个字节 $count = 4; } else if(substr($high,0,6) == '111110') { // 截取5个字节 $count = 5; } else if(substr($high,0,7) == '1111110') { // 截取6个字节 $count = 6; } // echo $count,'<br />'; $res .= substr($str,$offset,$count); $chars += 1; $offset += $count; } return $res; } echo utf8sub($str,200); ?>