PHP Reference · String Functions
PHP mb_str_split() function
Reference for PHP mb_str_split(): split a string into characters or fixed-size groups of characters safely for UTF-8 text, with encodings and edge cases.
mb_str_split() is the multibyte-aware version of str_split(). It splits a string into an array of characters (or groups of characters) according to a character encoding, so é, ж or 日 are never cut apart.
It belongs to the mbstring extension and was added in PHP 7.4. The encoding defaults to the value of mb_internal_encoding(), which is UTF-8 in current PHP versions.
<?php print_r(mb_str_split("añb")); // ["a", "ñ", "b"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
mb_str_split(string $string, int $length = 1, ?string $encoding = null): array
| Name | Description |
|---|---|
$string |
The string to split. |
$length |
The number of characters per chunk. Must be at least 1. |
$encoding |
Character encoding such as "UTF-8". null uses the internal encoding. |
Return value: an array of strings. The last element may be shorter than $length. An empty string gives an empty array.
Errors: throws a ValueError if $length is less than 1 or if the encoding is not valid.
Usage notes
- Code points, not grapheme clusters. A base letter followed by a combining accent, or an emoji sequence such as a family emoji, becomes several elements. For user-perceived characters you need the
intlextension (grapheme_*functions) or a regex with\X. - Requires mbstring. If the extension is missing, the function does not exist; check with
function_exists()in portable code. - Invalid UTF-8 does not throw; bad bytes become single elements, so validate with
mb_check_encoding()first when it matters. - Slower than
str_split()because it decodes characters. Use the plain version for ASCII-only data. - Alternative:
preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY)works without mbstring when PCRE has UTF-8 support.