最新消息: 新版网站上线了!!!

php中文截字不乱码的函数

<?php
    function myMbSubstr($str, $start, $length, $charset){
        $charsets["utf-8"] = $charsets["utf8"] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $charsets["gb2312"] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $charsets["gbk"] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $charsets["big5"] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        
        preg_match_all($charsets[$charset], $str, $matches);    #按照指定编码将字符串切分成一个数组
        
        #var_dump($matches);
        
        $substr = implode("", array_slice($matches[0], $start, $length));    #获取数组的子数组,并将子数组的元素连接起来
        
        return $substr;
    }
    
    $str = "I'm a 码农";
    
    echo "<br>" . myMbSubstr($str, 0, 7, "utf8") . "<br>";
    echo mb_substr($str, 0, 7, "utf8");
?>

转载请注明:谷谷点程序 » php中文截字不乱码的函数