How to correctly count Chinese words in PHP

Source: Internet
Author: User

How to correctly count Chinese words in PHP? This is a problem that has plagued me for a long time, there are many functions in PHP to calculate the length of the string, such as the following example, respectively, the strlen mb_strlen mb_strwidth three function to test the length of the statistical string, to see the Chinese counted as a few bytes:

EchoStrlen( "Hello abc"  ;# output 9 echo mb_strlen ( "Hello abc"  ' UTF-8 ' ) ;# output 5echo mb_strwidth ( Hello abc" 7    

From the above test, we can see: The Chinese characters are strlen counted as 3 bytes, regardless of the English language mb_strlen , all 1 bytes, and the mb_strwidth Chinese is counted as 2 bytes, so mb_strwidth we want to : Chinese 2 bytes, English 1 bytes .

The same interception string is also recommended mb_strimwidth to use, but also according to the Chinese 2 bytes, the English 1 byte method after the calculation, and if the number of words than the interception requirements, this function can also be added in the last side of the ' ... '.

mb_strimwidth($post_excerpt,0,240,‘...‘,‘utf-8‘);

Note that the last addition of the ' Utf-8 ' encoding parameter, can avoid the problem of Chinese truncation garbled.

How to correctly count Chinese words in PHP

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.