How to correctly count Chinese characters? _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags ereg
How to correctly count Chinese characters ?. PHP code: compile functionccStrLen ($ str) # calculate the length of a mix of Chinese and English strings {$ ccLen0; $ ascLenstrle PHP code: Compile :--------------------------------------------------------------------------------
Function ccStrLen ($ str) # calculate the length of a Chinese/English string.
{
$ CcLen = 0;
$ AscLen = strlen ($ str );
$ Ind = 0;
$ HasCC = ereg ("[xA1-xFE]", $ str); # identify whether there are Chinese characters
$ HasAsc = ereg ("[x01-xA0]", $ str); # identify whether ASCII characters exist
If ($ hasCC &&! $ HasAsc) # only Chinese characters
Return strlen ($ str)/2;
If (! $ HasCC & $ hasAsc) # only Ascii characters
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) # extract Chinese and English strings from the left
{
$ AscLen = strlen ($ str); if ($ ascLen <= $ len) return $ str;
$ HasCC = ereg ("[xA1-xFE]", $ str); # Same as above
$ HasAsc = ereg ("[x01-xA0]", $ str );
If (! $ HasCC) return substr ($ str, 0, $ len );
If (! $ HasAsc)
If ($ len & 0x01) # if the length is odd
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 );
}
--------------------------------------------------------------------------------
__________________
── ┬ ── ┐

Invalid argument function ccStrLen ($ str) # calculate the length of a string that contains both Chinese and English characters {$ ccLen = 0; $ ascLen = strle...

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.