适用于无法安装mbstring扩展的环境
注:尽量使用mbstring扩展,纯php代码执行效率比扩展慢几十倍;
function mb_substr($str, $start = 0, $length = 0, $encode = 'utf-8') { /* 该编码每个非英文字符的字节长度 */ $encode_len = $encode == 'utf-8' ? 3 : 2; /* 计算开始字节 */ for($byteStart = $i = 0; $i < $start; ++$i) { $byteStart += ord($str{$byteStart}) < 128 ? 1 : $encode_len; /* 当起始坐标超出字符串,则返回空值 */ if( $str{$byteStart} == '' ) return ''; } /* 计算字节长度 */ for($i = 0, $byteLen = $byteStart; $i < $length; ++$i) $byteLen += ord($str{$byteLen}) < 128 ? 1 : $encode_len; return substr( $str, $byteStart, $byteLen-$byteStart ); }
