Use PHP functions to calculate the length of Chinese and English strings. _ PHP Tutorial

Source: Internet
Author: User
The PHP function is used to calculate the length of Chinese and English strings ,. Using PHP functions to calculate the length of Chinese and English strings, this article describes how to use PHP functions to calculate the length of Chinese and English strings. Share it with you for your reference. The specific implementation uses PHP functions to calculate the length of Chinese and English strings,

This example describes how to use PHP functions to calculate the length of Chinese and English strings. Share it with you for your reference. The specific implementation method is as follows:

Generally, we 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 ().

The code is as follows:

The code is as follows:

Echo $ str = 'php point passthrough ';

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. the code is as follows:

The code is as follows:

<? Php
Function _ strlen ($ str)
{
Preg_match_all ("/./us", $ str, $ matches );
Return count (current ($ matches ));
}

Echo _ strlen ("PHP point-to-point"); // 6
?>

I hope this article will help you with PHP programming.

Examples in this article describe how to use PHP functions to calculate the length of Chinese and English strings. Share it with you for your reference. Implementation...

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.