Using PHP strlen() to Calculate String Length
This article explains PHP's strlen() function, its syntax, demonstrates how to calculate string lengths with and without surrounding spaces using code examples, and discusses important considerations such as encoding support and handling of special or multibyte characters.
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.
Below are concrete code examples.
Example 1: Calculating String Length
$str = "Hello, world!"; // define a string
echo strlen($str); // output the string lengthThe output is:
13Example 2: Ignoring Spaces When Calculating String Length
$str = " Hello, world! "; // string with leading/trailing spaces
echo strlen($str); // length including spaces
echo strlen(trim($str)); // length after trimming spacesThe output is:
23
13From these examples, it is clear that strlen() is a very common function for string processing. It can quickly count string length and is useful in 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 results.
When using strlen() , also be aware of special characters or Chinese characters, as they occupy different numbers of bytes in different encodings, which 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.