Backend Development 5 min read

Using PHP strlen() to Get String Length: Syntax, Examples, and Tips

This article explains the PHP strlen() function, its syntax, and provides multiple code examples for measuring string length, checking for empty strings, validating length limits, and handling multibyte characters, while noting the need for mb_strlen() for Unicode strings.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP strlen() to Get String Length: Syntax, Examples, and Tips

In PHP development we often need to obtain the length of a string for various operations, and PHP provides the very useful strlen() function for this purpose. This article introduces the function and presents several example codes.

The syntax of strlen() is:

int strlen ( string $string )

It accepts a single string argument and returns the length of that string in bytes.

Below are some common usage examples:

1. Get the length of a string

$foo = "Hello, World!";
$length = strlen($foo);
echo "字符串的长度是:" . $length; // Output: 字符串的长度是:13

2. Check if a string is empty

$bar = "";
if (strlen($bar) == 0) {
    echo "字符串为空";
} else {
    echo "字符串不为空";
}

3. Verify that a string length does not exceed a limit

$password = "abcd";
$length = strlen($password);
if ($length > 8) {
    echo "密码长度过长,请重新输入";
} else {
    echo "密码长度符合要求";
}

4. Get the length of a multibyte string

$chinese = "你好,世界!";
$length = strlen($chinese);
echo "字符串的长度是:" . $length; // Output: 字符串的长度是:15

It is important to note that strlen() counts bytes, not characters. For multibyte strings such as Chinese, each character occupies multiple bytes, so the byte length may exceed the character count. To obtain the number of characters, use mb_strlen() instead.

Measuring string length is frequently used for input validation, string processing, and various comparisons. By using strlen() , developers can easily obtain string lengths and perform subsequent operations.

Summary

This article introduced PHP's strlen() function, which can be used to obtain the length of a string. Through several code examples we demonstrated how to use the function to check if a string is empty, verify length constraints, and handle multibyte strings. Mastering this function is essential for string manipulation and input validation.

Java learning material download

C language learning material download

Frontend learning material download

C++ learning material download

PHP learning material download

Backend DevelopmentphpCode Examplestring 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.