PHP 8 reference · Multibyte String Functions

PHP mb_trim() Function

Strip whitespace from both ends of a string, including Unicode spaces such as the non-breaking space. Added in PHP 8.4.

PHP 8 Since 8.4

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

mb_trim(string $string, ?string $characters = null, ?string $encoding = null): string

Parameters

ParameterDescription
string The input string.
characters optional The characters to strip; by default every Unicode whitespace character.
encoding optional The character encoding; defaults to mb_internal_encoding() (UTF-8).

Return value

The trimmed string.

Examples

Unicode whitespace
<?php
$input = "\u{00A0}  hello\u{3000}";
var_dump(trim($input));
var_dump(mb_trim($input));

Output

string(12) "   hello "
string(5) "hello"

Run this on your computer — see “Get Started” for setup.

Custom characters, and mb_ltrim()
<?php
echo mb_trim("«Bonjour»", "«»"), "\n";
echo mb_ltrim("¡¡Hola"), "|", mb_ltrim("¡¡Hola", "¡"), "\n";

Output

Bonjour
¡¡Hola|Hola

Run this on your computer — see “Get Started” for setup.

mb_ltrim() and mb_rtrim(), also added in PHP 8.4, strip only the start or the end.

Version history

VersionChange
PHP 8.4Added

In other languages

Was this page helpful?