- php教程首页
- php函数
php 中英文字符串截取函数
•php函数•阅读 339 - /**
- * php获取字符串中英文混合长度
- * @param $str string 字符串
- * @param $$charset string 编码
- * @return 返回长度,1中文=1位,2英文=1位
- */
- function strlength($str,$charset='utf-8'){
- if($charset=='utf-8') $str = iconv('utf-8','gb2312',$str);
- $num = strlen($str);
- $cnnum = 0;
- for($i=0;$i<$num;$i++){
- if(ord(substr($str,$i+1,1))>127){
- $cnnum++;
- $i++;
- }
- }
- $ennum = $num-($cnnum*2);
- $number = ($ennum/2)+$cnnum;
- return ceil($number);
- }
- //测试输出长度都为15 //开源代码phpfensi.com
- $str1 = '测试测试测试测试测试测试测试测';
- $str2 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
- $str3 = 'aa测试aa测试aa测试aa测试aaaaaa';
- echo strlength($str1,'gb2312');
- echo strlength($str2,'gb2312');
- echo strlength($str3,'gb2312');