php截取函数,可代替mb_substr

On 07/31/2010, in php, by kilobug

适用于无法安装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 );
}
Tagged with:  

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

无觅相关文章插件,快速提升流量