PHP 8 reference · Multibyte String Functions
PHP mb_strlen() Function
Return the number of characters in a string, counting é or 日 as one character. The UTF-8-safe version of strlen().
PHP 8 Since 4.0
Syntax
mb_strlen(string $string, ?string $encoding = null): int
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
encoding optional |
The character encoding; defaults to mb_internal_encoding() (UTF-8). |
Return value
The number of characters.
Examples
<?php
$word = "naïve café";
echo strlen($word), "\n"; // bytes
echo mb_strlen($word), "\n"; // characters
Output
12 10
<?php
$bio = "Ich heiße Jürgen und wohne in Köln.";
echo mb_strlen($bio) <= 40 ? "fits" : "too long", "\n";
Output
fits
Use mb_strlen() whenever a length limit is shown to people, such as a 40-character bio: users count
characters, not bytes.
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
len()· Pythonstring.length· JavaScript
Related
strlen()· Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters.mb_substr()· Return part of a string by character position, so multibyte characters are never cut in half. The UTF-8 version of substr().mb_str_split()· Split a multibyte string into an array of characters, or of chunks of n characters. The UTF-8-safe str_split().- PHP Strings · tutorial