Overview
KB
Technical FAQ
PHP Manual
CSS2 Manual
HTML Manual
JS Guide
JS Reference
PhpDock Manual
Nu-Coder Manual
PhpExpress Manual
PHP Joomla
Development
Learn PHP
 
<mb_rtrimmb_send_mail>
^Multibyte String FunctionsLast updated: Mon, 26 Oct 2026

mb_scrub

(PHP 7 >= 7.2.0, PHP 8)

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

Description

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

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.

Parameters

string

The input string.

encoding

The 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 Values

The string result with invalid byte sequences replaced.

Errors/Exceptions

As of PHP 8.0.0, a ValueError is thrown if encoding is an invalid encoding. Prior to PHP 8.0.0, an E_WARNING was emitted instead.

Changelog

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

Examples

Example #1 Byte-level replacement performed by mb_scrub()

bin2hex() is used here because terminals, browsers and fonts may render an ill-formed byte sequence with a replacement character of their own, which hides what the string actually contains.

<?php

// 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";

?>

The above example will output:

41ff42
413f42
41efbfbd42

Example #2 Using mb_scrub() before UTF-8 aware processing

PCRE patterns using the u modifier reject subjects that are not well-formed UTF-8. Scrubbing the input first makes it acceptable.

<?php

$input = "A\xFFB";

var_dump(preg_match_all('/./us', $input));
echo preg_last_error_msg(), "\n";

$clean = mb_scrub($input, 'UTF-8');

var_dump(preg_match_all('/./us', $clean));

?>

The above example will output:

bool(false)
Malformed UTF-8 characters, possibly incorrectly encoded
int(3)

See Also


<mb_rtrimmb_send_mail>
^Multibyte String FunctionsLast updated: Mon, 26 Oct 2026