Home > Backend Development > PHP Tutorial > 如何正确统计中文字数?_PHP

如何正确统计中文字数?_PHP

WBOY
Release: 2016-06-01 12:39:31
Original
1063 people have browsed it

PHP代码:--------------------------------------------------------------------------------
function ccStrLen($str) #计算中英文混合字符串的长度
{
$ccLen=0;
$ascLen=strlen($str);
$ind=0;
$hasCC=ereg("[xA1-xFE]",$str); #判断是否有汉字
$hasAsc=ereg("[x01-xA0]",$str); #判断是否有ASCII字符
if($hasCC && !$hasAsc) #只有汉字的情况
return strlen($str)/2;
if(!$hasCC && $hasAsc) #只有Ascii字符的情况
return strlen($str);
for($ind=0;$ind {
if(ord(substr($str,$ind,1))>0xa0)
{
$ccLen++;
$ind++;
}
else
{
$ccLen++;
}
}
return $ccLen;
}
function ccStrLeft($str,$len) #从左边截取中英文混合字符串
{
$ascLen=strlen($str); if($ascLen $hasCC=ereg("[xA1-xFE]",$str); #同上
$hasAsc=ereg("[x01-xA0]",$str);
if(!$hasCC) return substr($str,0,$len);
if(!$hasAsc)
if($len & 0x01) #如果长度是奇数
return substr($str,0,$len+$len-2);
else
return substr($str,0,$len+$len);
$cind=0;$flag=0;
while($cind {
if(ord(substr($str,$cind,1)) $cind++;
}
if($flag & 0x01)
return substr($str,0,$len);
else
return substr($str,0,$len-1);
}

--------------------------------------------------------------------------------



__________________

┌──┬──┐
│ ╭┘  │
│ ╰┐╭╮│
├┐┌┼┘└┤
│╰╯└╮ │
│  ┌╯ │
└──┴──┘

参考
http://www.csdn.net/develop/Read_Article.asp?Id=20454

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template