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

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 /**
 * 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
$str1 = '测试测试测试测试测试测试测试测';
$str2 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$str3 = 'aa测试aa测试aa测试aa测试aaaaaa';
echo strLength($str1,'gb2312');
echo strLength($str2,'gb2312');
echo strLength($str3,'gb2312');

你可能感兴趣的:(PHP)