大网数据广告活动
PHP 语言与运行手册

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

· 52CE 我爱测

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

mb_scrub

(PHP 7 >= 7.2.0, PHP 8)

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

说明

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.

参数

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.

返回值

The string result with invalid byte sequences replaced.

错误/异常

从 PHP 8.0.0 起,如果 encoding 是无效编码, 则会抛出 ValueError。 在 PHP 8.0.0 之前,会发出 E_WARNING。

更新日志

版本 说明
8.0.0 现在 encoding 可以为 null。
8.0.0 现在,如果 encoding 是无效编码, 会抛出 ValueError。 以前会发出 E_WARNING 并返回 false。

示例

示例 #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";

?>

以上示例会输出:

41ff42
413f42
41efbfbd42

示例 #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));

?>

以上示例会输出:

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

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。