Obtain the natural length of a string containing Chinese and English characters.

Source: Internet
Author: User
Test the awareness code instance of encoding: {code ...} the result is strlen (), which calculates the number of bytes of the string. one English character is 1 byte, the Chinese character is 2 byte in GBK encoding, and the UTF8 is 3 byte, therefore, the number of bytes is 3*3 + 312mb_strlen () and mb_strin... test the awareness of encoding

Code example:

$ Str = 'Hello everyone ABC'; echo strlen ($ str); echo'
'; Echo mb_strlen ($ str, 'utf-8 ');

The result is 12, 6.

  • Strlen () calculates the number of bytes of a string. an English character is 1 byte, a Chinese character is 2 byte in GBK encoding, and UTF8 is 3 byte, therefore, the number of bytes is 3*3 + 3 = 12.

  • Mb_strlen () requires mb_string extension, mixed mb_strlen (string $ str [, string $ encoding = mb_internal_encoding ()]). The first parameter is the string to be checked, the second parameter is the encoding format. multi-byte characters are recorded as 1.


Test the awareness of encoding

Code example:

$ Str = 'Hello everyone ABC'; echo strlen ($ str); echo'
'; Echo mb_strlen ($ str, 'utf-8 ');

The result is 12, 6.

  • Strlen () calculates the number of bytes of a string. an English character is 1 byte, a Chinese character is 2 byte in GBK encoding, and UTF8 is 3 byte, therefore, the number of bytes is 3*3 + 3 = 12.

  • Mb_strlen () requires mb_string extension, mixed mb_strlen (string $ str [, string $ encoding = mb_internal_encoding ()]). The first parameter is the string to be checked, the second parameter is the encoding format. multi-byte characters are recorded as 1.

For more articles about the natural length of Chinese and English strings, refer to the PHP Chinese website!

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.