Using PHP strlen() Function: Basics, Multibyte and Special Character Handling
This article explains the PHP strlen() function, demonstrates its basic usage with code examples, discusses limitations with multibyte and special characters, and shows how to use mb_strlen() to correctly measure string length in various encoding scenarios.
strlen() is a commonly used string function in PHP that returns the length of a given string. Its usage is straightforward: pass a string as the argument and the function returns its length.
Basic Usage:
You can call strlen() directly with a string variable as shown below:
<code>$str = "Hello World";
$length = strlen($str);
echo "字符串的长度是:{$length}";</code>Output:
<code>字符串的长度是:11</code>In this example, a string variable $str is defined, strlen() calculates its length, the result is stored in $length , and echo outputs the length.
Multibyte Character Handling:
When dealing with multibyte characters, strlen() counts bytes, not characters, which can lead to incorrect lengths. To handle this, PHP provides mb_strlen() that counts characters based on the specified encoding.
<code>$str = "你好,世界";
$length = mb_strlen($str, 'UTF-8');
echo "字符串的长度是:{$length}";</code>Output:
<code>字符串的长度是:5</code>Here mb_strlen() correctly calculates the length of the multibyte string by specifying the UTF-8 encoding.
Special Character Handling:
Special characters such as escaped sequences may occupy multiple bytes, causing strlen() to return an inaccurate length.
<code>$str = "Hello \n World";
$length = strlen($str);
echo "字符串的长度是:{$length}";</code>Output:
<code>字符串的长度是:14</code>The string contains a newline character represented by two characters (backslash and n), so the total byte length is 14 instead of the visible character count of 11. To obtain the actual character count, use mb_strlen() with the appropriate encoding.
Conclusion:
The strlen() function is a simple and useful tool for calculating string length in PHP. When working with multibyte or special characters, consider using mb_strlen() to obtain accurate character counts.
Mastering strlen() is essential for PHP developers to handle string length calculations effectively.
PHP Learning Recommendations:
Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Advanced – Recommended Course
Workerman+TP6 Real‑time Chat System – Limited Time Offer
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.