PHP报错 iconv(): Detected an illegal character in input string

PHP代码报错如下:

代码如下:

$length = strLength('嗨暼足球啊');
var_dump($length);die;

function strLength($str,$charset='utf-8'){
    //GB2312表示的是简体中文,不支持像"囧"之类的更为复杂的汉字以及一些特殊字符,导致报错
    // if($charset=='utf-8') $str = iconv('utf-8','gb2312',$str);
    //忽略了不能转换的字符,避免了出错但却不能够正确地输出(即空白不输出)//结果输出为4
    // if($charset=='utf-8') $str = iconv('utf-8','gb2312//IGNORE',$str);
    //可以正确地输出,因为GBK支持的字符范围更广//结果输出为5
    if($charset=='utf-8') $str = iconv('utf-8','GBK',$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);
}


猜你喜欢

转载自blog.csdn.net/weixin_38728964/article/details/81016400
今日推荐