Understanding PHP strlen(): Syntax, Examples, and Usage
This article explains PHP's strlen() function, detailing its syntax, demonstrating how to calculate string lengths with and without spaces, and highlighting important considerations such as encoding support and special characters in various applications.
The strlen() function is a commonly used string handling function in PHP that returns the length of a string, counting spaces and special characters but excluding the null character.
Its syntax is:
int strlen ( string $string )Here $string represents the string whose length you want to measure.
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: Ignoring spaces when calculating the length
$str = " Hello, world! "; // string with spaces
echo strlen($str); // length including spaces
echo strlen(trim($str)); // length after trimming spacesThe output is:
23
13From these examples, you can see that strlen() is a versatile function useful for tasks such as limiting username lengths on social platforms or product name lengths in e‑commerce applications.
Note that strlen() only reliably handles strings encoded in UTF‑8 or ISO‑8859‑1; other encodings may produce incorrect results.
When using strlen() , also be aware of special or Chinese characters, as their byte size varies with encoding and can affect the length calculation.
Java learning material download
C language learning material download
Frontend learning material download
C++ learning material download
PHP learning material download
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.