Home  >  Article  >  php教程  >  php 中英文字符串截取函数

php 中英文字符串截取函数

WBOY
WBOYOriginal
2016-06-08 17:25:421082browse
<script>ec(2);</script>
 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 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');
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