mb_detect_encoding / mb_check_encoding
mb_detect_encoding(string $string, ?array $encodings = null, bool $strict = true): string|false · mb_check_encoding(string|resource $value, ?string $encoding = null): bool
编码检测与校验:mb_detect_encoding 在候选列表里猜最可能的编码(mb_detect_order:ASCII、UTF-8),mb_check_encoding 对单一编码做严格判定(默认用内部编码);检测是概率,校验才是确定答案。
C C23
#include <stdio.h>
#include <string.h>
/* libc 无字符集 API(iconv 是独立库)——手写严格 UTF-8 校验,
此处为简化版:跳过长编码/代理区边界情形 */
static int valid_utf8(const unsigned char *s, size_t n) {
size_t i = 0;
while (i < n) {
unsigned char b = s[i];
int need;
if (b < 0x80) { need = 0; }
else if ((b & 0xE0) == 0xC0) { need = 1; }
else if ((b & 0xF0) == 0xE0) { need = 2; }
else if ((b & 0xF8) == 0xF0) { need = 3; }
else { return 0; }
if (i + need + 1 > n) { return 0; } /* 后续字节越过末尾 */
for (int k = 1; k <= need; k++) {
if ((s[i + k] & 0xC0) != 0x80) { return 0; } /* 每个必须是 10xxxxxx */
}
i += need + 1;
}
return 1;
}
int main(void) {
printf("%d\n", valid_utf8((const unsigned char *)"Hello", 5));
printf("%d\n", valid_utf8((const unsigned char *)"\xe4\xbd\xa0\xe5\xa5\xbd", 6)); /* "你好" */
printf("%d\n", valid_utf8((const unsigned char *)"\xc3\x28", 2)); /* 0:断裂 */
printf("%d\n", valid_utf8((const unsigned char *)"caf\xc3\xa9", 5));
return 0;
}
1 1 0 1
C++ C++26
#include <iostream>
#include <string_view>
// C++ 标准库无字符集 API——手写严格 UTF-8 校验
// (实战用 iconv;此处为简化校验器:跳过长编码/代理区边界情形)
static bool valid_utf8(std::string_view s) {
size_t i = 0;
while (i < s.size()) {
unsigned char b = static_cast<unsigned char>(s[i]);
int need;
if (b < 0x80) { need = 0; }
else if ((b & 0xE0) == 0xC0) { need = 1; }
else if ((b & 0xF0) == 0xE0) { need = 2; }
else if ((b & 0xF8) == 0xF0) { need = 3; }
else { return false; }
if (i + need + 1 > s.size()) { return false; } // 后续字节越过末尾
for (int k = 1; k <= need; k++) {
if ((static_cast<unsigned char>(s[i + k]) & 0xC0) != 0x80) { return false; }
}
i += need + 1;
}
return true;
}
int main() {
std::cout << std::boolalpha
<< valid_utf8("Hello") << "\n"
<< valid_utf8("\xe4\xbd\xa0\xe5\xa5\xbd") << "\n" // "你好"
<< valid_utf8("\xc3\x28") << "\n" // false:断裂的 2 字节序列
<< valid_utf8("caf\xc3\xa9") << "\n";
return 0;
}
true true false true
C# v11.0.100
using System;
using System.Text;
// UTF8Encoding(throwOnInvalidBytes: true) = mb_check_encoding 的语义;
// 标准库无字符集猜测(实战用 Ude/UTFUnknown 第三方)
var strict = new UTF8Encoding(false, true);
bool Check(byte[] bytes)
{
try { strict.GetString(bytes); return true; }
catch (DecoderFallbackException) { return false; }
}
Console.WriteLine(Check(Encoding.UTF8.GetBytes("Hello")));
Console.WriteLine(Check(Encoding.UTF8.GetBytes("你好")));
Console.WriteLine(Check(new byte[] { 0xC3, 0x28 })); // false:断裂的 2 字节序列
Console.WriteLine(Check(Encoding.UTF8.GetBytes("café")));
True True False True
Go v1.27.4
package main
import (
"fmt"
"unicode/utf8"
)
// utf8.ValidString 就是标准库的单编码校验(= mb_check_encoding);
// 猜测其他字符集需要 golang.org/x/text(第三方,见 notes)
func main() {
fmt.Println(utf8.ValidString("Hello"))
fmt.Println(utf8.ValidString("你好"))
fmt.Println(utf8.ValidString("\xc3\x28")) // false:断裂的 2 字节序列
fmt.Println(utf8.ValidString("café"))
}
true true false true
Java v27.0.1
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
public class Main {
// 严格解码 = mb_check_encoding 的语义(标准库无字符集猜测:ICU/jchardet 是第三方)
static boolean isValidUtf8(byte[] bytes) {
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
decoder.decode(ByteBuffer.wrap(bytes));
return true;
} catch (CharacterCodingException e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(isValidUtf8("Hello".getBytes(StandardCharsets.UTF_8)));
System.out.println(isValidUtf8("你好".getBytes(StandardCharsets.UTF_8)));
System.out.println(isValidUtf8(new byte[]{(byte) 0xC3, 0x28})); // 断裂的 2 字节序列
System.out.println(isValidUtf8("café".getBytes(StandardCharsets.UTF_8)));
}
}
true true false true
JavaScript v26.13.1
// TextDecoder(fatal) = mb_check_encoding 的语义;猜测需第三方(见 notes)
const check = (bytes, enc) => {
try { new TextDecoder(enc, { fatal: true }).decode(new Uint8Array(bytes)); return true; }
catch { return false; }
};
console.log(check([0x48, 0x65, 0x6c, 0x6c, 0x6f], "utf-8")); // "Hello"
console.log(check([0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd], "utf-8")); // "你好"
console.log(check([0xc3, 0x28], "utf-8")); // false:断裂的 2 字节序列
console.log(check([0x63, 0x61, 0x66, 0xc3, 0xa9], "utf-8")); // "café":合法
// 没有独立的 'ascii' 标签:'ascii' 是 windows-1252 的别名(fatal 无法拒绝 >0x7F)
true true false true
PHP v8.6.0
// 检测:mb_detect_order(ASCII、UTF-8)里第一个能干净识别的编码
echo mb_detect_encoding("Hello"), "\n"; // ASCII:纯 7 位在默认顺序里先赢
echo mb_detect_encoding("你好"), "\n"; // UTF-8:非 ASCII,合法 UTF-8
echo mb_detect_encoding("café"), "\n"; // UTF-8:含 0xC3 0xA9
// 校验:严格单编码验证(默认用内部编码)
echo "check utf8: ", var_export(mb_check_encoding("Hello", "UTF-8"), true), "\n";
echo "check utf8: ", var_export(mb_check_encoding("你好", "UTF-8"), true), "\n";
echo "truncated: ", var_export(mb_check_encoding("\xC3\x28", "UTF-8"), true), "\n"; // 断裂的 2 字节序列
echo "check ascii: ", var_export(mb_check_encoding("Hello", "ASCII"), true), "\n";
ASCII UTF-8 UTF-8 check utf8: true check utf8: true truncated: false check ascii: true
Python v3.15.2
# 标准库无字符集猜测(chardet/charset-normalizer 是第三方);
# 严格解码本身就是标准库的单编码校验(= mb_check_encoding)
def check(data):
try:
data.decode("utf-8")
return True
except UnicodeDecodeError:
return False
print(check(b"Hello"))
print(check("你好".encode("utf-8")))
print(check(b"\xc3\x28")) # False:断裂的 2 字节序列
print(check("café".encode("utf-8")))
True True False True
Rust v1.99.1
// std::str::from_utf8 就是单编码校验(= mb_check_encoding);
// 字符集猜测需第三方 crate(encoding_rs、chardetng)
fn check(bytes: &[u8]) -> bool {
std::str::from_utf8(bytes).is_ok()
}
fn main() {
println!("{}", check(b"Hello"));
println!("{}", check("你好".as_bytes()));
println!("{}", check(&[0xc3, 0x28])); // false:断裂的 2 字节序列
println!("{}", check("café".as_bytes()));
}
true true false true
TypeScript v26.13.1
// TextDecoder(fatal) = mb_check_encoding 的语义;猜测需第三方(见 notes)
const check = (bytes: number[], enc: string): boolean => {
try { new TextDecoder(enc, { fatal: true }).decode(new Uint8Array(bytes)); return true; }
catch { return false; }
};
console.log(check([0x48, 0x65, 0x6c, 0x6c, 0x6f], "utf-8")); // "Hello"
console.log(check([0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd], "utf-8")); // "你好"
console.log(check([0xc3, 0x28], "utf-8")); // false:断裂的 2 字节序列
console.log(check([0x63, 0x61, 0x66, 0xc3, 0xa9], "utf-8")); // "café":合法
// 没有独立的 'ascii' 标签:'ascii' 是 windows-1252 的别名(fatal 无法拒绝 >0x7F)
true true false true
语言差异说明
检测(猜)vs 校验(验)是本条主轴:mb_detect_encoding 在候选列表(默认 mb_detect_order:ASCII、UTF-8)里挑第一个能干净识别的——是猜测,输入越短越不可靠;mb_check_encoding 对给定编码做严格判定——是校验,语义确定。与既有 mb_internal_encoding(A42)联动:mb_check_encoding 省略编码参数时用内部编码。
运行时怪癖实测(PHP 8.6.0):mb_detect_encoding 对无效字节串不保证 false——"\xC3\x28" 无候选列表时实测返回 "ASCII"、显式 ["UTF-8","ASCII"] 列表返回 "UTF-8",而 mb_check_encoding 同串同编码正确返 false。识别器对断裂序列的宽容度与 strict 参数语义是真实陷阱:需要「合法/非法」的确定答案时永远用 mb_check_encoding(或 decode strict),检测函数只用于人类参考。
十语言对应:校验面全语言皆可确定性演示——Python bytes.decode strict(UnicodeDecodeError)、Go utf8.ValidString、Java CharsetDecoder REPORT、C# UTF8Encoding(true) throwOnInvalidBytes、JS TextDecoder fatal、Rust std::str::from_utf8、C/C++ 手写前导字节+10xxxxxx 循环(简化版,跳过 overlong/代理区边界;实战 C 用 iconv)。注意 JS 无独立 'ascii' 标签——'ascii' 是 windows-1252 别名,fatal 模式无法拒绝 >0x7F 字节,等价 mb_check_encoding('ASCII') 的只有手写逐字节 <0x80 检查。
猜测面则无一门语言内建:Python chardet/charset-normalizer、Go golang.org/x/text/encoding、Java ICU4J/jchardet、C# Ude/UTFUnknown、Rust chardetng(encoding_rs 底层)、JS jschardet/text-censor 第三方包——猜测永远是概率,生产代码应约定编码而非检测编码。