How to treat Chinese characters and various special punctuation characters as 2 characters in length during UTF-8 Coding

Source: Internet
Author: User
This title is a bit of a second... I don't know how to describe it. Let's take a look. The maximum length of a registered user is 12 in Chinese and 24 in English. How can we verify this in PHP? The length of a Chinese character in strlen is 3 in UTF-8 encoding. Using mb_strl... is a bit of a title... I don't know how to describe it. Let's take a look.

The length limit that is frequently seen when registering users is:
You can enter 12 Chinese characters and 24 English letters.
How can we verify this in PHP?

UTF-8 Encoding
The length of a Chinese character using strlen is 3.
The length of a Chinese character using mb_strlen is 1.

Reply content:

This title is a bit of a second... I don't know how to describe it. Let's take a look.

The length limit that is frequently seen when registering users is:
You can enter 12 Chinese characters and 24 English letters.
How can we verify this in PHP?

UTF-8 Encoding
The length of a Chinese character using strlen is 3.
The length of a Chinese character using mb_strlen is 1.

It seems that you do not know that there is a function named mb_strwidth.

The characters encoded by the UTF-8 may be 1 ~ It consists of three bytes. The specific number can be determined by the first byte. (Theoretically it may be longer, but it is assumed that the length cannot exceed 3 bytes)

Encoding method of UTF-8

  1. The first byte is greater than 224, which together with the second byte after it forms a UTF-8 character
  2. The first byte is greater than 192 less than 224, and it is a UTF-8 character with the first byte after it
  3. Otherwise, the first byte is an English character (including numbers and a small part of punctuation marks ).

You can specify the encoding for obtaining the length:

mb_strlen($str,'gb2312')

It's easy. Convert the code to cp936, and then use strlen directly.

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.