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 * 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');