php截取中文字符串 GB2312 utf-8

本文提供了两种用于中文字符串截取的PHP函数:一种适用于UTF-8编码,另一种适用于GB2312编码。通过正则表达式匹配和字符计数实现了对中文字符的精确截断,并在超过指定长度时添加省略号。
UTF-8截取中文字符串
   function Cn_Substr($string, $length) {
        preg_match_all("/[\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]/", $string, $info);  
        for($i=0; $i<count($info[0]); $i++) {
 $wordscut .= $info[0][$i];
 $j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
 if ($j > $length - 3) {
 return $wordscut." ...";
 }
        }
        return join('', $info[0]);
   }
GB2312截取中文字符串
   function Cn_Substrs($strs,$lens){
      if (strlen($strs)<$lens) {
          $nstrs=$strs;
      }else{
          $mlens=$lens;
          for ($i=0;$i<=strlen($strs) && $mlens>0;$i++){
             $chars=substr($strs,$i,1);
             if(ord($chars)>0xa0 ) { 
                $i++;
                $mlens -=2;;
             }else{
                $mlens--;
             }
          }
          $nstrs=substr($strs,0,$i)."...";
      }
      return $nstrs;
   }

 

转载于:https://www.cnblogs.com/ygcool/p/5395402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值