发新话题
打印

php计算汉字、字母、数字组成字符串的长度

php计算汉字、字母、数字组成字符串的长度

function sstrlen($str,$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; } //例子 echo sstrlen('去看看ta','gbk'); //结果为5

TOP

发新话题