mb_scrub()

mb_scrub() — Replace ill-formed byte sequences with the substitute character.

Built-in function of PHP 8.5. The manual lists it as available in PHP 7 >= 7.2.0, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Perform a character set conversion from the specified encoding, or the default encoding if no encoding was specified, to the same encoding. This has the effect of replacing any invalid byte sequences with the substitute character.

Signature

mb_scrub(string $string, ?string $encoding = null): string

Parameters

ParameterTypeWhat it takes
$stringstringThe input string.
$encoding?stringThe encoding used to interpret string. If it is omitted or null, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting will be used.

Return value

The string result with invalid byte sequences replaced.

Example

A runnable snippet:

// The byte 0xFF cannot appear in a valid UTF-8 string. $input = "A\xFFB"; echo bin2hex($input), "\n"; // The default substitute character is "?" (0x3F). echo bin2hex(mb_scrub($input, 'UTF-8')), "\n"; // U+FFFD REPLACEMENT CHARACTER is encoded as EF BF BD in UTF-8. mb_substitute_character(0xFFFD); echo bin2hex(mb_scrub($input, 'UTF-8')), "\n";

Output:

41ff42 413f42 41efbfbd42

Changelog

VersionChange
8.0.0encoding is nullable now.
8.0.0Now throws a ValueError if encoding is an invalid encoding. Previously, an E_WARNING was emitted and false was returned.

See also

mb_substitute_character(), mb_check_encoding(), mb_convert_encoding()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page mb_scrub() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.