Understanding PHP strlen(): Syntax, Examples, and Usage
This article explains PHP's strlen() function, detailing its syntax, demonstrating how to calculate string lengths—including handling spaces and trimming—and highlighting important considerations such as character encoding and special characters, with clear code examples and output explanations.
strlen() is a commonly used PHP string handling function that calculates the length of a string, including spaces and special characters but excluding the null character.
The syntax of the strlen() function is as follows:
int strlen ( string $string )Here, $string represents the string whose length is to be calculated.
Below, we look at some concrete code examples:
Example 1: Calculating the length of a string
$str = "Hello, world!"; // define a string
echo strlen($str); // output the string lengthThe output is:
13Example 2: Calculating string length while ignoring spaces
$str = " Hello, world! "; // define a string with spaces
echo strlen($str); // output the string length
echo strlen(trim($str)); // output the length after trimming spacesThe output is:
23
13From the examples, it can be seen that the strlen() function is widely used for string processing; it quickly counts string length and can be applied to scenarios such as limiting user nickname length on social sites or product name length in e‑commerce.
Note that strlen() only supports UTF‑8 and ISO‑8859‑1 encoded strings; using other encodings may produce incorrect length calculations.
When using strlen() , be aware of special or Chinese characters, as they may occupy different byte counts in various encodings, affecting the length result.
PHP Practice
Scan the QR code to receive free learning materials
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.