Backend Development 3 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP strlen(): Syntax, Examples, and Usage

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 length

The output is:

13

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

The output is:

23
13

From 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

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

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