Home >php教程 >PHP源码 >php中截取汉字,避免半个字节的问题

php中截取汉字,避免半个字节的问题

WBOY
WBOYOriginal
2016-06-08 17:32:13943browse
<script>ec(2);</script>
1. $In 要截取的字符串, $num要截取的长度, 返回截取的字符串
public function substrGB($in,$num)
    {
      //$num=16;
      $pos=0;
      $byteNum=0;
      $out="";
      while($num){
   
    $c=mb_substr($in,$pos,1,"EUC-JP");
    if($c=="n") break;
    if(strlen($c)==1){
      $pos++;
      $byteNum++;
      if($byteNum>$num) break;
      $out.=$c;                       
    }
    else
      {
        $pos++;
        $byteNum=$byteNum+2;
        if($byteNum>$num) break;
        $out.=$c;                  
      }
      }
      return $out;
    } 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn