Home > Backend Development > PHP Tutorial > How to get the length of Chinese string in php

How to get the length of Chinese string in php

WBOY
Release: 2016-07-25 09:07:14
Original
1797 people have browsed it
  1. $str = 'Hello world!';
  2. echo strlen($str); // Output 12
  3. ?>
Copy the code

However, it comes with PHP In the function, strlen and mb_strlen both calculate the length by calculating the number of bytes occupied by the string. Under different encoding conditions, the number of bytes occupied by Chinese is different. Under GBK/GB2312, Chinese characters occupy 2 bytes, while under UTF-8, Chinese characters occupy 3 bytes.

  1. $str = 'Hello world! ';
  2. echo strlen($str); // Output 12 under GBK or GB2312, 18 under UTF-8
  3. ?>
Copy code

And we often need to judge when judging the length of a string It is the number of characters, not the number of bytes occupied by the string, such as this php code under UTF-8:

  1. $name = 'Zhang Gengchang';
  2. $len = strlen($name);
  3. // Output FALSE, because three Chinese characters occupy 9 bytes under UTF-8
  4. if($len >= 3 && $len <= 8){
  5. echo 'TRUE';
  6. }else{
  7. echo 'FALSE';
  8. }
  9. ?>
Copy code

So there is What convenient and practical method can be used to obtain the length of a string containing Chinese characters? You can use regular rules to calculate the number of Chinese characters, divide by 2 under GBK/GB2312 encoding, divide by 3 under UTF-8 encoding, and finally add the length of the non-Chinese string, but this is too troublesome, WordPress There is a more beautiful piece of code in , which is as follows:

  1. $str = 'Hello, world! ';
  2. preg_match_all('/./us', $str, $match);
  3. echo count($match[0]); // Output 9
  4. ?>
Copy code

Use regular expressions The formula splits the string into single characters, and directly uses count to calculate the number of matching characters, and then we get the result we want.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template