Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. strlen() / mb_strlen()

strlen() / mb_strlen() Since: PHP 4(2000)

Returns the length of a string. For strings that contain multibyte characters, use mb_strlen() to get the correct character count.

Syntax

// Returns the number of bytes.
strlen($string);

// Returns the number of characters. Supports multibyte characters.
mb_strlen($string, $encoding);

Functions

FunctionDescription
strlen($string)Returns the number of bytes in a string. ASCII characters count as 1 byte; Japanese characters in UTF-8 count as 3 bytes each.
mb_strlen($string, $encoding)Returns the number of characters in a string. The second argument (encoding) is optional; if omitted, the internal encoding is used.

Return Value

strlen() returns the number of bytes in a string as an integer. mb_strlen() returns the number of characters as an integer.

Sample Code

<?php
// Get the length of an ASCII string.
$str = "Hello";
echo strlen($str); // Outputs '5'.

// Get the byte count of a string containing multibyte characters.
$name = "Taro Yamada";
echo strlen($name); // Outputs '11'.

// Use mb_strlen() to get the correct character count.
echo mb_strlen($name, "UTF-8"); // Outputs '11'.

// Useful for validating user input length.
$username = "John Smith";
if (mb_strlen($username, "UTF-8") > 20) {
	echo "Username must be 20 characters or fewer.";
} else {
	echo "Username accepted."; // This line is output.
}

// The length of an empty string is 0.
echo strlen(""); // Outputs '0'.

Notes

strlen() returns the length of a string in bytes. ASCII characters are 1 byte each, but Japanese characters in UTF-8 are 3 bytes each, so strlen() will not return the correct character count for strings containing Japanese. Always use mb_strlen() when working with multibyte strings.

mb_strlen() is the multibyte-aware version of the function and returns the correct character count based on the specified encoding. The second argument specifies the encoding; if omitted, the encoding set by mb_internal_encoding() is used.

This function is commonly used to validate form input length or to check a string's length before extracting a substring. To search within a string, use strpos(). To extract a substring, use substr() / mb_substr().

If you find any errors or copyright issues, please .