Php calculates the length of a mix of Chinese and English strings-PHP source code

Source: Internet
Author: User
Php calculates the length of a mix of Chinese and English strings. php calculates the length of a mix of Chinese and English strings.

Script ec (2); script


Echo ccStrLen ($ str ),'';
Echo ccStrLeft ($ str, 3 );
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 );
}

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 cs ($ str)
{
$ CcLen = 0;
$ AscLen = strlen ($ str );
$ Ind = 0;
For ($ ind = 0; $ ind <$ ascLen; $ ind ++)
{
If (ord (substr ($ str, $ ind, 1)> 0xa0)
{
$ CcLen ++;
$ Ind ++;
}
Else
{
$ CcLen ++;
}
}
Return $ ccLen;
}

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.