Mastering PHP’s strlen(): How to Accurately Measure String Length

This article explains PHP's strlen() function, its syntax, and provides clear code examples showing how to calculate string lengths—including handling spaces and encoding considerations—for practical use cases like input validation.

php Courses
php Courses
php Courses
Mastering PHP’s strlen(): How to Accurately Measure String Length

strlen() is a commonly used PHP string function that calculates the length of a string, including spaces and special characters but excluding the null character.

The syntax is: int strlen ( string $string ) $string represents the string whose length is to be calculated.

Example 1: Calculate string length

$str = "Hello, world!"; // define a string
echo strlen($str); // output string length

The output is:

13

Example 2: Calculate length ignoring spaces

$str = "   Hello,   world!    "; // string with spaces
echo strlen($str); // length with spaces
echo strlen(trim($str)); // length after trimming spaces

The output is:

23
13

These examples show that strlen() is widely used for quickly counting string length, useful in scenarios such as limiting usernames on social sites or product name lengths in e‑commerce.

Note that strlen() only reliably handles UTF‑8 and ISO‑8859‑1 encoded strings; other encodings may produce incorrect results.

When using strlen(), be aware of special or Chinese characters, as their byte size varies with encoding and can affect the length calculation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendphp-functionsstring lengthstrlen
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.