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

Encoding detection and validation: mb_detect_encoding guesses the likeliest encoding from a candidate list (mb_detect_order: ASCII, UTF-8), while mb_check_encoding strictly validates one encoding (defaulting to the internal one); detection is probabilistic, validation gives the definite answer.

C C23

C23
#include <stdio.h>
#include <string.h>

/* no charset API in libc (iconv is a separate lib) - hand-rolled strict UTF-8 check,
   simplified here: skips overlong/surrogate edge cases */
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; } /* continuation runs off the end */
        for (int k = 1; k <= need; k++) {
            if ((s[i + k] & 0xC0) != 0x80) { return 0; } /* each must be 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)); /* Chinese greeting in UTF-8 */
    printf("%d\n", valid_utf8((const unsigned char *)"\xc3\x28", 2)); /* 0: truncated */
    printf("%d\n", valid_utf8((const unsigned char *)"caf\xc3\xa9", 5));
    return 0;
}
Output
1
1
0
1

C++ C++26

C++26
#include <iostream>
#include <string_view>

// no charset API in the C++ standard library - hand-rolled strict UTF-8 check
// (real work: iconv; simplified validator here: skips overlong/surrogate edge cases)
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; } // continuation runs off the end
        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" // Chinese greeting in UTF-8
              << valid_utf8("\xc3\x28") << "\n" // false: truncated 2-byte sequence
              << valid_utf8("caf\xc3\xa9") << "\n";
    return 0;
}
Output
true
true
false
true

C# v11.0.100

v11.0.100
using System;
using System.Text;

// UTF8Encoding(throwOnInvalidBytes: true) = mb_check_encoding's semantics;
// no stdlib charset GUESSING (Ude/UTFUnknown third-party in real projects)
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: truncated 2-byte sequence
Console.WriteLine(Check(Encoding.UTF8.GetBytes("café")));
Output
True
True
False
True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"unicode/utf8"
)

// utf8.ValidString is the stdlib single-encoding CHECK (= mb_check_encoding);
// guessing other charsets needs golang.org/x/text (3rd party, see notes)
func main() {
	fmt.Println(utf8.ValidString("Hello"))
	fmt.Println(utf8.ValidString("你好"))
	fmt.Println(utf8.ValidString("\xc3\x28")) // false: truncated 2-byte sequence
	fmt.Println(utf8.ValidString("café"))
}
Output
true
true
false
true

Java v27.0.1

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 {
    // strict decode = mb_check_encoding's semantics (no stdlib charset GUESSING: ICU/jchardet are 3rd-party)
    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})); // truncated 2-byte sequence
        System.out.println(isValidUtf8("café".getBytes(StandardCharsets.UTF_8)));
    }
}
Output
true
true
false
true

JavaScript v26.13.1

v26.13.1
// TextDecoder(fatal) = mb_check_encoding's semantics; guessing needs 3rd-party (see 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")); // Chinese greeting: valid UTF-8
console.log(check([0xc3, 0x28], "utf-8")); // false: truncated 2-byte sequence
console.log(check([0x63, 0x61, 0x66, 0xc3, 0xa9], "utf-8")); // "café": valid
// no 'ascii' label of its own: 'ascii' aliases windows-1252 (fatal cannot reject >0x7F)
Output
true
true
false
true

PHP v8.6.0

v8.6.0
// detect: first encoding in mb_detect_order (ASCII, UTF-8) that identifies cleanly
echo mb_detect_encoding("Hello"), "\n";  // ASCII: pure 7-bit wins first in the default order
echo mb_detect_encoding("你好"), "\n";    // UTF-8: not ASCII, valid UTF-8
echo mb_detect_encoding("café"), "\n";   // UTF-8: contains 0xC3 0xA9
// check: strict single-encoding validation (defaults to the internal encoding)
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"; // broken 2-byte seq
echo "check ascii: ", var_export(mb_check_encoding("Hello", "ASCII"), true), "\n";
Output
ASCII
UTF-8
UTF-8
check utf8: true
check utf8: true
truncated: false
check ascii: true

Python v3.15.2

v3.15.2
# stdlib has no charset GUESSING (chardet/charset-normalizer are 3rd-party);
# strict decode IS the stdlib single-encoding CHECK (= 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: truncated 2-byte sequence
print(check("café".encode("utf-8")))
Output
True
True
False
True

Rust v1.99.1

v1.99.1
// std::str::from_utf8 IS the single-encoding CHECK (= mb_check_encoding);
// charset GUESSING needs third-party crates (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: truncated 2-byte sequence
    println!("{}", check("café".as_bytes()));
}
Output
true
true
false
true

TypeScript v26.13.1

v26.13.1
// TextDecoder(fatal) = mb_check_encoding's semantics; guessing needs 3rd-party (see 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")); // Chinese greeting: valid UTF-8
console.log(check([0xc3, 0x28], "utf-8")); // false: truncated 2-byte sequence
console.log(check([0x63, 0x61, 0x66, 0xc3, 0xa9], "utf-8")); // "café": valid
// no 'ascii' label of its own: 'ascii' aliases windows-1252 (fatal cannot reject >0x7F)
Output
true
true
false
true

Language differences

Detection (guessing) vs validation (verifying) is this entry's axis: mb_detect_encoding picks the first candidate that identifies cleanly (the default mb_detect_order: ASCII, UTF-8) — it is a guess, and the shorter the input the less reliable; mb_check_encoding decides strictly for one encoding — that is validation, with definite semantics. Chained with the existing mb_internal_encoding entry (A42): mb_check_encoding uses the internal encoding when the argument is omitted.

Runtime quirk verified (PHP 8.6.0): mb_detect_encoding does not guarantee false for invalid byte strings — "\xC3\x28" returned "ASCII" with no candidate list and "UTF-8" with an explicit ["UTF-8","ASCII"] list in testing, while mb_check_encoding correctly returns false for the same string and encoding. The recognizers' tolerance of truncated sequences and the strict parameter's semantics are a real trap: whenever you need a definite valid/invalid answer, use mb_check_encoding (or a strict decode); detection functions are for human reference only.

Ten-language counterparts: the validation face is deterministically demonstrable everywhere — 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++ hand-rolled lead-byte + 10xxxxxx loops (a simplified version skipping overlong/surrogate edge cases; real C work uses iconv). Note JS has no standalone 'ascii' label — 'ascii' aliases windows-1252, so fatal mode cannot reject >0x7F bytes; the true equivalent of mb_check_encoding('ASCII') is a hand-rolled per-byte <0x80 check.

The guessing face ships in no language: Python chardet/charset-normalizer, Go golang.org/x/text/encoding, Java ICU4J/jchardet, C# Ude/UTFUnknown, Rust chardetng (under encoding_rs), JS jschardet and friends are all third-party — guessing is always probabilistic; production code should agree on encodings, not detect them.