PHP 8 reference · Multibyte String Functions
PHP mb_substr() Function
Return part of a string by character position, so multibyte characters are never cut in half. The UTF-8 version of substr().
PHP 8 Since 4.0
Syntax
mb_substr(string $string, int $start, ?int $length = null, ?string $encoding = null): string
Parameters
| Parameter | Description |
|---|---|
string |
The input string. |
start |
The first character, from 0; negative counts from the end. |
length optional |
How many characters; null takes the rest. |
encoding optional |
The character encoding; defaults to mb_internal_encoding() (UTF-8). |
Return value
The extracted part.
Examples
<?php
$city = "Zürich";
echo mb_substr($city, 0, 2), "\n";
echo mb_substr($city, -3), "\n";
Output
Zü ich
<?php
$text = "Crème brûlée is a French dessert";
echo mb_strlen($text) > 15 ? mb_substr($text, 0, 15) . "…" : $text, "\n";
Output
Crème brûlée is…
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
slice()· Pythonstring.slice()· JavaScript
Related
substr()· Return part of a string, given a start position and an optional length. Negative values count from the end.mb_strlen()· Return the number of characters in a string, counting é or 日 as one character. The UTF-8-safe version of strlen().mb_strpos()· Find the character position of the first occurrence of a substring in a multibyte string. Returns false if not found.- PHP Strings · tutorial