Home  >  Article  >  Backend Development  >  How to calculate string length in php? Comparison of two methods

How to calculate string length in php? Comparison of two methods

青灯夜游
青灯夜游forward
2021-07-12 19:52:5514183browse

How to calculate string length in php? The following article will introduce to you two built-in functions strlen() and mb_strlen() in PHP to calculate the length of strings, and see their differences.

How to calculate string length in php? Comparison of two methods

Use the strlen() function

to return the length of the given string string.

Return value: If successful, the length of the string string is returned; if string is empty, returns 0.

Examples based on interview questions:

   $str = 'hello';
   echo strlen($str), &#39;<br>&#39;; //5
   
   $str1 = &#39;中国&#39;;
   echo strlen($str1), &#39;<br>&#39;; //6

   echo strlen($str4), &#39;<br>&#39;; //0

UTF-8 encodes a Chinese character and occupies 3 bytes gdk encodes a Chinese character and occupies 2 bytes

The following is the gdk encoding

$str2 = &#39;hello&#39;;
echo strlen($str2), &#39;<br>&#39;; //5
$str3 = &#39;中国&#39;;
echo strlen($str3), &#39;<br>&#39;; //4

echo strlen($str4), &#39;<br>&#39;; //0

Use the mb_strlen() function

—Get the length of the string

Return value: Return the number of characters contained in the string str with encoding encoding . Returns FALSE if the given encoding is invalid. encoding is the character encoding.

$str = '你好中国'; 
echo strlen($str), '0c6dc11e160d3b678d68754cc175188a'; //12
$str1 = '你好中国';
echo mb_strlen($str1, 'utf-8'), '0c6dc11e160d3b678d68754cc175188a'; //4

gbk Two bytes and one character

strlen is the calculation of string 'byte' length - string length

mb_strlen is to calculate the length of string 'characters'

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to calculate string length in php? Comparison of two methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete