Understanding PHP strlen(): Syntax, Examples, and Usage
This article explains PHP's strlen() function, detailing its syntax, parameters, and behavior, and provides two practical code examples showing how to obtain string lengths with and without surrounding spaces, while noting encoding and special‑character considerations.
The strlen() function is a commonly used string handling function in PHP; it calculates the length of a string (including spaces and special characters, but excluding the null character).
Syntax of the strlen() function:
<code>int strlen ( string $string )</code>Here, $string represents the string whose length is to be calculated.
Concrete code examples:
Example 1: Calculating the length of a string
<code>$str = "Hello, world!"; //定义一个字符串
echo strlen($str); //输出字符串的长度
</code>The output is:
<code>13</code>Example 2: Calculating string length while ignoring spaces
<code>$str = " Hello, world! "; //定义一个带有空格的字符串
echo strlen($str); //输出字符串的长度
echo strlen(trim($str)); //输出去除空格后字符串的长度
</code>The output is:
<code>23
13</code>From the above examples, it can be seen that the strlen() function is widely used for string handling. It can quickly count a string's length, suitable not only for general string processing tasks but also for scenarios such as limiting user nickname lengths on social sites or product name lengths in e‑commerce.
Note that the strlen() function only supports UTF‑8 and ISO‑8859‑1 encoded strings; using other encodings may lead to incorrect length calculations.
When using strlen() , be aware that special characters or Chinese characters may occupy different numbers of bytes under various encodings, affecting the length result.
PHP learning recommendations:
Vue3 + Laravel8 + Uniapp Beginner to Real‑World Development Tutorial
Vue3 + TP6 + API Social E‑commerce System Development Course
Swoole From Beginner to Master 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.