PHP (1)-process Chinese character strings in php: strlen and mb_strlen

Source: Internet
Author: User
Play PHP (a)-php processing Chinese character string length: strlen and mb_strlen note: This article is a small series of original, if reproduced, please indicate the source: http://blog.csdn.net/u012116457/article/details/42536039

I officially started learning PHP today, but I accidentally discovered something that requires special attention when using PHP.

For example:

 
 

The output result of this code is: name Length: 6

First, let's look at why this problem occurs: the built-in string length function strlen () in PHP cannot correctly process Chinese strings. what it returns is the number of bytes occupied by the strings. For GB2312 Chinese encoding, strlen obtains two times the number of Chinese characters, and for the UTF-8 encoding of Chinese, is three times the difference (in the UTF-8 encoding, A Chinese character occupies 3 bytes ).


If you want to use the strlen function to calculate the length of a string containing Chinese characters, the following example is taken online:

 0xa0) {             $tmpstr.=substr($str,$i,2);             $i++;         } else             $tmpstr.=substr($str,$i,1);     }     return $tmpstr; }?>

However, apart from this, we can use the mb_strlen function to calculate:

 
 

The output result is: the name length is: 2


The usage of mb_strlen is similar to that of strlen, except that it has a second optional parameter for specifying character encoding.

It should be noted that mb_strlen is not a PHP core function. before using it, make sure that. the "php_mbstring.dll" line is loaded in ini to ensure that the "extension = php_mbstring.dll" line exists and is not commented out. Otherwise, the problem of undefined functions may occur.

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.