UTF-8 GBK下PHP获取字符串长度

UTF-8 GBK下PHP获取字符串长度,是langwan写的,贴过来大家分享,完美的解决了PHP下获取UTF-8或者GBK字符集的字符串长度问题!

/*

* 统计字符串长度
*@author langwan
*@param $str 被统计字符串

*/

function sstrlen($str) {
global $charset;
$n = 0; $p = 0; $c = ”;
$len = strlen($str);
if($charset == ‘utf-8′) {
for($i = 0; $i < $len; $i++) {
$c = ord($str{$i});
if($c > 252) {
$p = 5;
} elseif($c > 248) {
$p = 4;
} elseif($c > 240) {
$p = 3;
} elseif($c > 224) {
$p = 2;
} elseif($c > 192) {
$p = 1;
} else {
$p = 0;
}
$i+=$p;$n++;
}
} else {
for($i = 0; $i < $len; $i++) {
$c = ord($str{$i});
if($c > 127) {
$p = 1;
} else {
$p = 0;
}
$i+=$p;$n++;
}
}

return $n;
}

Popularity: 15%

One Response to “UTF-8 GBK下PHP获取字符串长度”

使用mb_strlen($str, ‘utf-8′)可以统计多字节字符的宽度,GBK编码更换相应的编码就可以了.

Leave a Reply:

Name (required):
Mail (will not be published) (required):
Website:
Comment (required):
XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>