php 中文字串截取亂碼

來源:互聯網
上載者:User

標籤:php   亂碼   字串切割   

       PHP截取字串如果是英文直接用substr就可以了,但對於中文字元,用substring可能會導致亂碼,那麼將如何解決呢?

1、通過函數mb_substr實現

       說明:mb_substr($str, $start, $length, $encoding);通過該函數即可,但需要載入php_mbstring.dll擴充。

案例:

<?php $str = ‘這是一個字串切割函數‘; echo "mb_substr:".mb_substr($str, 0, 7, ‘utf-8‘); ?>

2、通過函數mb_strcut實現


說明:mb_strcut() 和 mb_substr() 類似,都是從一個字串中提取子字串,但是按位元組數來執行,而不是字元個數。 如果截斷位置位於多位元組字元兩個位元組的中間,將於該字元的第一個位元組開始執行。 這也是和 substr() 函數的不同之處,後者簡單地將字串在位元組之間截斷,這將導致一個畸形的位元組序列。

3、通過編寫的函數(支援UTF-8和GB2312)

案例:

<?php /* Utf-8、gb2312都支援的漢字截取函數 cut_str(字串, 截取長度, 開始長度, 編碼); 編碼預設為 utf-8 開始長度預設為 0 */ function cut_str($string, $sublen, $start = 0, $code = ‘UTF-8‘) {      $string = str_replace(array(‘&‘, ‘"‘, ‘<‘, ‘>‘), array(‘&‘, ‘"‘, ‘<‘, ‘>‘), $string);     if($code == ‘UTF-8‘)      {          $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";          preg_match_all($pa, $string, $t_string);          if(count($t_string[0]) - $start > $sublen) return join(‘‘, array_slice($t_string[0], $start, $sublen))."...";          return join(‘‘, array_slice($t_string[0], $start, $sublen));       }       else       {          $start = $start*2;          $sublen = $sublen*2;          $strlen = strlen($string);          $tmpstr = ‘‘;          for($i=0; $i< $strlen; $i++)          {             if($i>=$start && $i< ($start+$sublen))             {                 if(ord(substr($string, $i, 1))>0xa0)                 {                     $tmpstr.= substr($string, $i, 2);                 }                 else                 {                     $tmpstr.= substr($string, $i, 1);                 }              }              if(ord(substr($string, $i, 1))>0xa0) $i++;           }           if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";           return $tmpstr;         } } $str = "這是一個字串切割函數"; echo cut_str($str, 8, 0, ‘gb2312‘); ?>


php 中文字串截取亂碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.