PHP怎么计算汉字字数?
<?php
header('Content-type : text/html; Charset=UTF-8');//页面编码为utf-8
/**
*参数$str为字符串
*参数$charset为字符集,不设置则为utf-8,务必和页面编码和文件编码保持一致.
*/
function abslen($str,$charset='utf-8'){
$charset=strtolower($charset);
if(empty($str)){
return 0;
}
if(function_exists('mb_strlen')){
return mb_strlen($str,$charset);
}else{
$preg= '/./i';
if($charset=='utf-8') $preg.='u';
$n = preg_match_all($preg, $str);
return $n;
}
}
/*调用函数*/
echo abslen('哎哟,你们都在这里啊!');
echo abslen('哎哟,你们都在这里啊!','GB2312');
?> |
|