mb_scrub
mb_scrub(string $string, ?string $encoding = null): string
把编码中非法字节序列替换为替换符(默认 ?,可用 mb_substitute_character 设为 U+FFFD)——数据清洗入口:脏输入先 scrub 再处理。
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
/* C 没有标准解码器;手写:ASCII 原样复制,
每个非法/截断的 UTF-8 字节替换为 U+FFFD(EF BF BD) */
const unsigned char bad[] = {0x61, 0xFF, 0x62, 0xC3, 0};
unsigned char out[64] = {0}; /* 零初始化:短输入也不残留垃圾 */
size_t o = 0;
for (size_t i = 0; i < 4; i++) {
unsigned char b = bad[i];
if (b < 0x80) {
out[o++] = b;
} else {
out[o++] = 0xEF; out[o++] = 0xBF; out[o++] = 0xBD; /* U+FFFD */
}
}
int total = 0, repl = 0;
for (size_t j = 0; j < o;) {
if (out[j] == 0xEF && out[j + 1] == 0xBF && out[j + 2] == 0xBD) { repl++; j += 3; }
else { j++; }
total++;
}
printf("%d\n", total); /* 4 个字符 */
printf("%d\n", repl); /* 2 个替换符 */
for (size_t j = 0; j < o; j++) printf("%02x", out[j]);
printf("\n"); /* 61efbfbd62efbfbd */
return 0;
}
4 2 61efbfbd62efbfbd
C++ C++26
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main() {
const std::string bad = "a\xff" "b\xc3";
// 手写 scrub:非法/截断的首字节替换为 U+FFFD(EF BF BD)
std::string out;
for (unsigned char b : bad) {
if (b < 0x80) {
out += static_cast<char>(b);
} else {
out += "\xEF\xBF\xBD";
}
}
int total = 0, repl = 0;
for (size_t j = 0; j < out.size();) {
if (out.compare(j, 3, "\xEF\xBF\xBD") == 0) { repl++; j += 3; }
else { j++; }
total++;
}
std::cout << total << "\n" << repl << "\n";
std::ostringstream hex;
for (unsigned char c : out) {
hex << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(c);
}
std::cout << hex.str() << "\n";
return 0;
}
4 2 61efbfbd62efbfbd
C# v11.0.100
byte[] bad = { 0x61, 0xff, 0x62, 0xc3 };
// .NET 的 UTF-8 解码器默认把非法字节替换为 U+FFFD:
// GetString 就是 scrub
string fixedText = System.Text.Encoding.UTF8.GetString(bad);
Console.WriteLine(fixedText.Length); // 4
int n = 0;
foreach (char c in fixedText) {
if (c == '\uFFFD') n++;
}
Console.WriteLine(n); // 2
var hex = new System.Text.StringBuilder();
foreach (byte b in System.Text.Encoding.UTF8.GetBytes(fixedText)) {
hex.AppendFormat("{0:x2}", b);
}
Console.WriteLine(hex); // 61efbfbd62efbfbd
4 2 61efbfbd62efbfbd
Go v1.27.4
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
func main() {
bad := "a\xffb\xc3"
// strings.ToValidUTF8:每段非法字节串替换为替换符
fixed := strings.ToValidUTF8(bad, "\uFFFD")
fmt.Println(utf8.RuneCountInString(fixed)) // 4
fmt.Println(strings.Count(fixed, "\uFFFD")) // 2
fmt.Printf("%x\n", fixed) // 61efbfbd62efbfbd
fmt.Println(utf8.ValidString(fixed)) // true:现在是干净 UTF-8
}
4 2 61efbfbd62efbfbd true
Java v27.0.1
import java.nio.ByteBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
byte[] bad = {(byte) 0x61, (byte) 0xff, (byte) 0x62, (byte) 0xc3};
CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE) // errors='replace' 的对应物
.onUnmappableCharacter(CodingErrorAction.REPLACE);
String fixed = dec.decode(ByteBuffer.wrap(bad)).toString();
System.out.println(fixed.length()); // 4
int n = 0;
for (int i = 0; i < fixed.length(); i++) {
if (fixed.charAt(i) == '\uFFFD') n++;
}
System.out.println(n); // 2
StringBuilder hex = new StringBuilder();
for (byte b : fixed.getBytes(StandardCharsets.UTF_8)) {
hex.append(String.format("%02x", b));
}
System.out.println(hex); // 61efbfbd62efbfbd
}
}
4 2 61efbfbd62efbfbd
JavaScript v26.13.1
const bad = new Uint8Array([0x61, 0xff, 0x62, 0xc3]);
// fatal:false(默认)把非法字节替换为 U+FFFD;
// fatal:true 则直接抛错——严格版的对应物
const dec = new TextDecoder("utf-8", { fatal: false });
const fixed = dec.decode(bad);
console.log(fixed.length); // 4(码元;U+FFFD 占 1)
console.log((fixed.match(/\uFFFD/g) || []).length); // 2
console.log(Buffer.from(fixed, "utf-8").toString("hex")); // 61efbfbd62efbfbd
4 2 61efbfbd62efbfbd
PHP v8.6.0
// mb_scrub:向同一编码做一次往返,非法字节就地替换。
// 替换符默认是 '?'——设成 U+FFFD 作为标准清洗标记:
mb_substitute_character(0xFFFD);
$bad = "a\xffb\xc3"; // \xc3 开了个 2 字节序列却戛然而止:截断
$fixed = mb_scrub($bad, 'UTF-8');
var_dump(mb_strlen($fixed)); // 现在是 4 个字符
var_dump(mb_substr_count($fixed, "\u{FFFD}")); // 2 个替换标记
var_dump(bin2hex($fixed)); // 61efbfbd62efbfbd:看清幸存者
var_dump(mb_check_encoding($fixed, 'UTF-8')); // true:干净 UTF-8,可安全处理
int(4) int(2) string(16) "61efbfbd62efbfbd" bool(true)
Python v3.15.2
bad = b"a\xffb\xc3"
# errors='replace' 就是 Python 版 scrub:每个非法字节 → U+FFFD。
# 严格版对应物是 errors='strict'(抛错)——PHP 没有 raise 模式
fixed = bad.decode("utf-8", errors="replace")
print(len(fixed)) # 4
print(fixed.count("\ufffd")) # 2
print(fixed.encode("utf-8").hex()) # 61efbfbd62efbfbd
4 2 61efbfbd62efbfbd
Rust v1.99.1
fn main() {
let bad: Vec<u8> = vec![0x61, 0xff, 0x62, 0xc3];
// from_utf8_lossy 就是 scrub:每段非法字节串 → U+FFFD
let fixed = String::from_utf8_lossy(&bad); // Cow:已合法时直接借用
println!("{}", fixed.chars().count()); // 4
println!("{}", fixed.matches('\u{FFFD}').count()); // 2
let hex: String = fixed.bytes().map(|b| format!("{:02x}", b)).collect();
println!("{}", hex); // 61efbfbd62efbfbd
}
4 2 61efbfbd62efbfbd
TypeScript v26.13.1
const bad = new Uint8Array([0x61, 0xff, 0x62, 0xc3]);
// fatal:false(默认)把非法字节替换为 U+FFFD
const dec = new TextDecoder("utf-8", { fatal: false });
const fixed = dec.decode(bad);
console.log(fixed.length); // 4
console.log((fixed.match(/\uFFFD/g) || []).length); // 2
console.log(Buffer.from(fixed, "utf-8").toString("hex")); // 61efbfbd62efbfbd
4 2 61efbfbd62efbfbd
语言差异说明
C:无标准解码器——手写(示例:ASCII 透传、非法字节补 U+FFFD 三字节);完整性要按 UTF-8 语法状态机走,示例对演示字节做了简化;glib 的 g_utf8_make_valid 是现成库方案。
C++:同 C 手写(示例用 std::string + 手工替换);无标准「lossy 解码」API——std::wstring_convert 已弃用,现实方案是 ICU 或手写状态机。
C#:Encoding.UTF8.GetString 默认带替换回退(fatal 之外没有开关)——GetString 就是 scrub;显式控制用 EncoderFallback/DecoderFallback 自定义替换物;严格版不存在(只能先验 GetByteCount 类前置检查)。
Go:strings.ToValidUTF8(s, repl) 是最直接的对应物——替换符自选(示例给 U+FFFD);每段连续非法字节合并成一个替换符;utf8.ValidString 做清洗后验收。
Java:CharsetDecoder 三态——REPLACE(示例,等价 errors='replace')/IGNORE/REPORT(抛异常,等价 strict);PHP 没有抛错模式,Java 有。
JavaScript:TextDecoder 的 fatal:false(默认)即 scrub——fatal:true 抛 TypeError,严格版内建;替换符固定 U+FFFD 不可换(WHATWG encoding 标准)。
PHP:mb_scrub(7.2+)= 向同一编码做一次转换、非法字节换成替换符;替换符默认 ?(0x3F),不是 U+FFFD——示例先 mb_substitute_character(0xFFFD) 再 scrub 才得到 U+FFFD(0xEFBFBD);只支持替换模式、无 strict 抛错版;数据清洗场景:不可信输入(上传文件、第三方 API)先 scrub 再交给 UTF-8 敏感的下游。
Python:bytes.decode(errors='replace') 是内建 scrub——替换符固定 U+FFFD;errors 家族:strict(抛)/ignore(删除)/replace(替换)/backslashreplace 等——可控行为最丰富。
Rust:String::from_utf8_lossy 是内建 scrub(返回 Cow<str>——字节本已合法时零拷贝借用);严格版 String::from_utf8 返回 Result;替换符固定 U+FFFD;每段非法字节合并为一个替换符(WHATWG 风格)。
TypeScript:同 JavaScript。