Understanding PHP strlen(): Syntax, Examples, and Usage

This article explains PHP's strlen() function, detailing its syntax, parameters, and behavior, and provides two practical code examples showing how to obtain string lengths with and without surrounding spaces, while noting encoding and special‑character considerations.

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

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

Syntax of the strlen() function:

int strlen ( string $string )

Here, $string represents the string whose length is to be calculated.

Concrete code examples:

Example 1: Calculating the length of a string

$str = "Hello, world!"; //定义一个字符串
 echo strlen($str); //输出字符串的长度

The output is:

13

Example 2: Calculating string length while ignoring spaces

$str = "   Hello,   world!    "; //定义一个带有空格的字符串
 echo strlen($str); //输出字符串的长度
 echo strlen(trim($str)); //输出去除空格后字符串的长度

The output is:

23
13

From the above examples, it can be seen that the strlen() function is widely used for string handling. It can quickly count a string's length, suitable not only for general string processing tasks but also for scenarios such as limiting user nickname lengths on social sites or product name lengths in e‑commerce.

Note that the strlen() function only supports UTF‑8 and ISO‑8859‑1 encoded strings; using other encodings may lead to incorrect length calculations.

When using strlen(), be aware that special characters or Chinese characters may occupy different numbers of bytes under various encodings, affecting the length result.

PHP learning recommendations:

Vue3 + Laravel8 + Uniapp Beginner to Real‑World Development Tutorial

Vue3 + TP6 + API Social E‑commerce System Development Course

Swoole From Beginner to Master Recommended Course

Workerman + TP6 Real‑time Chat System – Limited Time Offer!

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.

PHPcoding tutorialstring 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.