Backend Development 4 min read

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

This article explains PHP's strlen() function, covering its syntax, usage examples for measuring string length with and without surrounding spaces, important encoding considerations, and provides learning resources for further in PHP development.

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

strlen() is a commonly used PHP string function that returns the length of a string, counting spaces and special characters but excluding the terminating null byte.

Syntax of strlen()

<code>int strlen ( string $string )</code>

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

Code Examples

Example 1: Calculate string length

<code>$str = "Hello, world!"; // define a string
echo strlen($str); // output the length of the string</code>

The output is:

<code>13</code>

Example 2: Length ignoring surrounding spaces

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

The output is:

<code>23
13</code>

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

Note that strlen() works correctly with UTF‑8 and ISO‑8859‑1 encoded strings; other encodings may produce inaccurate results.

When using strlen() , be aware that special characters or Chinese characters may occupy multiple bytes depending on the encoding, affecting the length calculation.

PHP Learning Recommendations

Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial

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

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System (Limited Offer)

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

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.