PHP is simple and effective in calculating the length of Chinese and English strings

Source: Internet
Author: User
We all know that English characters take up one byte, while Chinese characters gbk take up two, and utf8 take up three. many people think that php calculates the string length as the strlen () function, it calculates the length of a byte rather than the length of a character.

We all know that English characters take up one byte, while Chinese characters gbk take up two, and utf8 take up three. many people think that php calculates the string length as the strlen () function, it calculates the length of bytes rather than the length of characters. how can we get the length of characters in a string? There is also mb_strlen ()

Echo $ str = 'php point pass'; echo strlen ($ str); // 3*1 + 3*3 = 12 echo mb_strlen ($ str, 'gb2312 '); // 3*1 + 3*2 = 9 echo mb_strlen ($ str, 'utf-8'); // 6

Sadly, the mb series functions are not the core functions of PHP and are not enabled by default. There is also a super simple method to break strings into individual characters through regular expressions, the number of characters is the length of the string:
 

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.