substr()
2条评论»写了个获取最新评论的函数,用substr截取,后面总会莫名其妙地多个乱码,原来 ,substr() 函数只能正确截取单字节字符串,所以针对双字节或多字节编码的字符就得自己动手了~···
function sysSubStr($String,$Length,$Append=false){
if (strlen($String) <= $Length ){
return $String;
}
else{
$I = 0;
while ($I < $Length){
$StringTMP = substr($String,$I,1);
if ( ord($StringTMP) >=224 ){
$StringTMP = substr($String,$I,3);
$I = $I + 3;
}
elseif( ord($StringTMP) >=192 ){
$StringTMP = substr($String,$I,2);
$I = $I + 2;
}else{
$I = $I + 1;
}
$StringLast[] = $StringTMP;
}
$StringLast = implode("",$StringLast);
if($Append){
$StringLast .= "...";
}
return $StringLast;
}
}
更多的在这里:http://www.codebit.cn/pub/html/php_mysql/tip/data/substr/
评论(2)
这是我用的一个函数: function utf8_substr($str,$start) { $end = @func_get_arg(2); if (function_exists('mb_strimwidth')) { $end*=2; $end+=3; return mb_strimwidth($str, $start, $end, '...', 'UTF-8'); } preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $ar); if($end) { return join("",array_slice($ar[0],$start,$end)); } else { return join("",array_slice($ar[0],$start)); } }
汗,既然都用mb_strimwidth了,为什么不直接用mb_substr截取?