本文实例讲述了php按字符无乱码截取中文的方法。分享给大家供大家参考。具体实现方法如下:

<"";
  $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程序设计有所帮助。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com