Skip to content
Tutorials Center
My learning

Topics

PHP Reference · String Functions

PHP mb_substr() function

Reference for PHP mb_substr(): extract part of a multibyte string by character position, negative offsets, the encoding argument and truncating UTF-8 safely.

mb_substr() is the multibyte-aware version of substr(). It counts characters (code points) in a given encoding instead of bytes, so it never cuts a UTF-8 character in half.

Use it whenever strings may contain accented letters, non-Latin scripts or emoji. It is part of the mbstring extension.

PHP
<?php
echo mb_substr("日本語のテキスト", 0, 3);   // 日本語
echo mb_substr("naïve café", -4);          // café

Try it

PHP substr() versus mb_substr()

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.

PHP Truncating and splitting safely

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

PHP
mb_substr(string $string, int $start, ?int $length = null, ?string $encoding = null): string
Name Description
$string The input string.
$start First character to include (0-based). Negative values count from the end.
$length Maximum number of characters. Negative: leave that many characters off the end. null: to the end.
$encoding The character encoding. null uses the internal encoding (UTF-8 by default).

Return value: the extracted part as a string; empty if nothing is selected.

Errors: a ValueError is thrown if $encoding is not a known encoding.

Usage notes

  • Characters are code points. A letter followed by a combining accent counts as two, so truncating can strip an accent from its letter. For truly user-visible characters, use the intl function grapheme_substr() if available.
  • Always cut with the matching family. Positions from mb_strpos() or mb_strlen() belong with mb_substr(); byte positions from strpos() belong with substr().
  • Slower than substr() on long strings for large offsets, since PHP has to walk the characters. Use substr() for ASCII-only or binary data.
  • Truncate with an ellipsis after counting characters, not bytes; see the second example.
  • Invalid input. Bytes that are not valid in the encoding give implementation-specific results; check with mb_check_encoding() first.
  • Splitting into pieces: mb_str_split().
  • Length: mb_strlen().