php中按字节截取字符串方法,(汉字占两个字节,字母占一个字节,页面编码必须为utf-8)

function esub($str, $length = 0) {

    if($length < 1){
        return $str;
    }

    //计算字符串长度
    $strlen = (strlen($str) + mb_strlen($str,"UTF-8")) / 2;
    if($strlen < $length){
        return $str;
    }

    if(mb_check_encoding($str,"UTF-8")){
        $str = mb_strcut(mb_convert_encoding($str, "GBK","UTF-8"), 0, $length, "GBK");
        $str = mb_convert_encoding($str, "UTF-8", "GBK");

    }else{

        return "不支持的文档编码";
    }

//    $str = rtrim($str," ,.。,-——(【、;‘“??《<@");
    return $str;
}

$str = "国际 CF210A 211A 212A 213A硒鼓(适用HP惠普CF210A 恩";

$a = esub($str,50);
echo $a;

你可能感兴趣的:(PHP常用小方法)