PHP获取中英文混合字符串长度及截取

1.字符串长度

PHP获取中英文混合字符串长度的实现代码如下,1中文=1位,2英文=1位,可自行修改

[php]
 
  1. /** 
  2. * PHP获取字符串中英文混合长度  
  3. * @param $str string 字符串 
  4. * @param $$charset string 编码 
  5. * @return 返回长度,1中文=1位,2英文=1位 
  6. */  
  7. function strLength($str,$charset='utf-8'){  
  8. if($charset=='utf-8') $str = iconv('utf-8','gb2312',$str);  
  9. $num = strlen($str);  
  10. $cnNum = 0;  
  11. for($i=0;$i<$num;$i++){  
  12. if(ord(substr($str,$i+1,1))>127){  
  13. $cnNum++;  
  14. $i++;  
  15. }  
  16. }  
  17. $enNum = $num-($cnNum*2);  
  18. $number = ($enNum/2)+$cnNum;  
  19. return ceil($number);  
  20. }  
  21.   
  22. //测试输出长度都为15  
  23. $str1 = '测试测试测试测试测试测试测试测';  
  24. $str2 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';  
  25. $str3 = 'aa测试aa测试aa测试aa测试aaaaaa';  
  26. echo strLength($str1,'gb2312');  
  27. echo strLength($str2,'gb2312');  
  28. echo strLength($str3,'gb2312');  

2.截取字符串函数

UTF8编码,在UTF8中,一个中文字符占3个字节

[php]

function msubstr($str, $start, $len) {  
  1.     $tmpstr = "";  
  2.     $strlen = $start + $len;  
  3.     for($i = 0; $i < $strlen; $i++){  
  4.         if(ord(substr($str, $i, 1)) > 127){  
  5.             $tmpstr.=substr($str, $i, 3);  
  6.             $i+=2;  
  7.         }else  
  8.             $tmpstr.= substr($str, $i, 1);  
  9.     }  
  10.     return $tmpstr;  
  11. }  
  12. echo msubstr("一二三天下致公english",0,10);  

GB2312编码,在gb2312中,一个中文字符占2个字节

[php]

<?php  
  1. function msubstr($str, $start, $len) {   //ȡ  
  2.    $tmpstr = "";  
  3.    $strlen = $start + $len;  
  4.    if(preg_match('/[/d/s]{2,}/',$str)){$strlen=$strlen-2;}  
  5.    for($i = 0; $i < $strlen; $i++) {  
  6.        if(ord(substr($str, $i, 1)) > 0xa0) {  
  7.            $tmpstr .= substr($str, $i, 2);  
  8.            $i++;  
  9.        } else  
  10.            $tmpstr .= substr($str, $i, 1);  
  11.      }  
  12.    return $tmpstr;  
  13.  }  
  14.     
  15. ?>  

编码兼容性良好的函数

[php]

function cc_msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)  
    1. {  
    2.     if(function_exists("mb_substr"))  
    3.         return mb_substr($str, $start, $length, $charset);  
    4.     elseif(function_exists('iconv_substr')) {  
    5.         return iconv_substr($str,$start,$length,$charset);  
    6.     }  
    7.     $re['utf-8']   = "/[/x01-/x7f]|[/xc2-/xdf][/x80-/xbf]|[/xe0-/xef][/x80-/xbf]{2}|[/xf0-/xff][/x80-/xbf]{3}/";  
    8.     $re['gb2312'] = "/[/x01-/x7f]|[/xb0-/xf7][/xa0-/xfe]/";  
    9.     $re['gbk']    = "/[/x01-/x7f]|[/x81-/xfe][/x40-/xfe]/";  
    10.     $re['big5']   = "/[/x01-/x7f]|[/x81-/xfe]([/x40-/x7e]|/xa1-/xfe])/";  
    11.     preg_match_all($re[$charset], $str, $match);  
    12.     $slice = join("",array_slice($match[0], $start, $length));  
    13.     if($suffix) return $slice."…";  
    14.     return $slice;  
    15. }  
浪漫家园,没事就来逛逛
原文地址:https://www.cnblogs.com/lovezbs/p/4497487.html