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.

php Courses
php Courses
php Courses
Using PHP strlen() to Calculate String Length

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 length

The output is:

13

Example 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 spaces

The output is:

23
13

From 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

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.

BackendPHPcodingstring 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.