# 如何正確統計中文字數？

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<\$ascLen;\$ind++)
{
if(ord(substr(\$str,\$ind,1))>0xa0)
{
\$ccLen++;
\$ind++;
}
else
{
\$ccLen++;
}
}
return \$ccLen;
}
function ccStrLeft(\$str,\$len) #從左邊截取中英文混合字串
{
\$ascLen=strlen(\$str); if(\$ascLen<=\$len) return \$str;
\$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<\$ascLen)
{
if(ord(substr(\$str,\$cind,1))<0xA1) \$flag++;
\$cind++;
}
if(\$flag & 0x01)
return substr(\$str,0,\$len);
else
return substr(\$str,0,\$len-1);
}

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

__________________

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

## Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD