實現中文字串截取無亂碼的方法

 

  1. 想要實現中文字串截取無亂碼的方法咱們首先確定會想到 mb_substr()
函數

  2. 若是不使用 PHP 自帶的函數,能夠本身封裝一個函數也能夠達到中文字符串的截取,這裏拿 GB2312 編碼來舉例,GB2312 中文編碼佔 2 個字節,同理 UTF-8 編碼也可使用編碼

 1 function GBsubstr($string, $start, $length) {
 2     if(strlen($string) > $length){
 3         $str = null;
 4         $len = $start + $length;
 5         for($i = $start; $i < $len; $i++){
 6             if(ord(substr($string, $i, 1)) > 0xa0){
 7             $str .= substr($string, $i, 2);  // 若是編碼爲UTF-8,這裏第三個參數改成 3  8             $i++;
 9             } else {
10                 $str .= substr($string, $i, 1);
11             }
12         }
13         return $str.'...';
14     }else{
15         return $string;
16     }
17 }
相關文章
相關標籤/搜索