Definition and Usage
- PHP Version
- 4.0.6+
The mb_strlen() function returns the length of a given string as a number.
Unlike the strlen() function, it supports multibyte strings, making it highly useful for determining the length of multibyte strings such as Chinese, Japanese, and Korean (CJK) text.
English letters and numbers are represented using 1 byte, whereas characters such as Chinese, Japanese, and Korean (CJK) are represented using 2 or more bytes.
Characters encoded with 2 or more bytes are referred to as multibyte characters.
Basic Example
$mb_str = 'こんにちは'; // Multibyte string (Japanese)
var_dump(mb_strlen($mb_str, 'UTF-8')); // int(5)
$str_1 = 'abcdef1234';
var_dump(mb_strlen($str_1, 'UTF-8')); // int(10)
/* Spaces are included in the string length */
$str_2 = 'abc def';
var_dump(mb_strlen($str_2, 'UTF-8')); // int(7)
$str_3 = ' abc def ';
var_dump(mb_strlen($str_3, 'UTF-8')); // int(9)
$str_4 = ' ';
var_dump(mb_strlen($str_4, 'UTF-8')); // int(1)
/* Empty string */
$str_5 = '';
var_dump(mb_strlen($str_5, 'UTF-8')); // int(0)
/* Boolean values (non-string type) */
var_dump(mb_strlen(true, 'UTF-8')); // int(1)
var_dump(mb_strlen(false, 'UTF-8')); // int(0)
Syntax
mb_strlen(string $string, ?string $encoding = null): int
Parameters
$string |
The string whose length will be measured. |
|---|---|
$encoding |
Optional. The character encoding to be used for the string.
|
Return Values
Returns the number of characters in the string as an integer based on the specified character encoding. Multibyte characters are counted as a single character.
Changelog
| Version | Description |
|---|---|
| 8.0.0 | The $encoding parameter can now accept null as a value. |
Things to Keep in Mind
When using the mb_strlen() function, the returned value may not always behave as expected depending on the type of the parameter.
Boolean Parameter Case
The mb_strlen() function also works with boolean values even though they are not strings.
trueis converted to the string'1', which has a character length of 1.falseis converted to an empty string (''), which has a character length of 0.
$str_1 = true;
var_dump(mb_strlen($str_1, 'UTF-8')); // int(1)
$str_2 = false;
var_dump(mb_strlen($str_2, 'UTF-8')); // int(0)
Things to Keep in Mind When Using null as the $encoding Value
Using null as the value for $encoding can be used as of PHP 8.0.0. Prior to PHP 8.0.0, an E_WARNING error is generated.
$mb_str = 'welcome!';
var_dump(mb_strlen($mb_str, null));
// Warning: mb_strlen(): Unknown encoding
$mb_str = 'welcome!';
var_dump(mb_strlen($mb_str, null)); // int(8)
References
See Also
- PHP strlen() Function – Get String Length
- PHP count() Function – Check Array Length
- PHP trim() Function – Removing Whitespace or Specified Characters from Both Ends of a String
- PHP substr() Function – Slice Strings by Position and Length
- PHP strpos() Function – Find First Substring Index
- PHP stripos() Function – Find First Substring Index (Case-Insensitive)