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

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

青灯夜游
Release: 2023-04-10 10:58:01
forward
14217 people have browsed it

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
Copy after login

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
Copy after login

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 = &#39;你好中国&#39;; 
echo strlen($str), &#39;<br>&#39;; //12
$str1 = &#39;你好中国&#39;;
echo mb_strlen($str1, &#39;utf-8&#39;), &#39;<br>&#39;; //4
Copy after login

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!

Related labels:
source:csdn.net
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