php按字元無亂碼截取中文的方法_php技巧

來源:互聯網
上載者:User

本文執行個體講述了php按字元無亂碼截取中文的方法。分享給大家供大家參考。具體實現方法如下:

<?php//$str 待截取的字串//$len 截取的字元個數//$chars 已經截取的字元數//$res  儲存的字串//$chars 儲存已經截取的字串個數//$offset 截取的位移量//$length 字串的位元組數//若$len>$str的字元個數,造成無謂的while迴圈,($offset<$length限定)function utf8sub($str,$len){  if($len<=0){    return ;  }  $res="";  $offset=0;  $chars=0;  $length=strlen($str);  while($chars<$len && $offset<$length){    $hign=decbin(ord(substr($str,$offset,1)));      if(strlen($hign)<8){        $count=1;      }elseif(substr($hign,0,3)=="110"){        $count=2;      }elseif(substr($hign,0,4)=="1110"){        $count=3;      }elseif(substr($hign,0,5)=="11110"){        $count=4;      }elseif(substr($hign,0,6)=="111110"){        $count=5;      }elseif(substr($hign,0,7)=="1111110"){        $count=6;      }    $res.=substr($str,$offset,$count);    $offset+=$count;    $chars+=1;  }  return $res;}function utf8sub1($str,$len){  $chars=0;  $res="";  $offset=0;  $length=strlen($str);  while($chars<$len && $offset<$length){    $hign=decbin(ord(substr($str,$offset,1)));    if(strlen($hign)<8){      $count=1;    }elseif($hign & "11100000"=="11000000"){      $count=2;    }elseif($hign & "11110000"=="11100000"){      $count=3;    }elseif($hign & "11111000"=="11110000"){      $count=4;    }elseif($hign & "11111100"=="11111000"){      $count=5;    }elseif($hign & "11111110"=="11111100"){      $count=6;    }    $res.=substr($str,$offset,$count);    $chars++;    $offset+=$count;  }  return $res;}$a="中華ah人民hdj";echo utf8sub($a,5);?>

希望本文所述對大家的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.