How to correctly count Chinese words?

Source: Internet
Author: User
Tags count ereg ord php code return strlen
Statistics | Chinese PHP code:--------------------------------------------------------------------------------
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)) &LT;0XA1) $flag + +;
$cind + +;
}
if ($flag & 0x01)
Return substr ($str, 0, $len);
Else
Return substr ($str, 0, $len-1);
}

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



__________________

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

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



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.