php 中英文字符串截取函数
Release: 2016-06-08 17:25:42
Original
1081 people have browsed it
<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 of this Website
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31