Method of Calculating Chinese and English String Length by PHP Function

  • 2021-07-26 07:05:06
  • OfStack

This paper describes the method of calculating the length of Chinese and English strings by using PHP function. Share it for your reference. The specific implementation method is as follows:

Generally speaking, we all know that English characters account for 1 byte, while Chinese characters gbk account for 2 characters and utf8 account for 3 characters. Many people have the impression that php calculates the string length as strlen () function, but in fact, it calculates the length of bytes instead of characters, so how to get the length of characters in a string? There is also mb_strlen ().

The specific code is as follows:

echo $str = 'PHP Point-to-point communication '; 
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

Hateful is that the functions of mb series are not the core functions of PHP, which are not turned on by default. There is also an ultra-simple method, which decomposes the string into individual characters by regularization, and calculates the number of characters as the length of the string. 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 communication ");  //6 
?>

I hope this article is helpful to everyone's PHP programming.


Related articles: