mb_scrub

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

Replaces ill-formed byte sequences with the substitute character (default ?, settable to U+FFFD via mb_substitute_character) - the data-cleaning gate: scrub dirty input before processing.

C C23

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

int main(void) {
    /* C has no standard decoder; hand-roll: copy ASCII, emit U+FFFD
       (EF BF BD) for every invalid/truncated UTF-8 byte */
    const unsigned char bad[] = {0x61, 0xFF, 0x62, 0xC3, 0};
    unsigned char out[64] = {0}; /* zero-init: no garbage on short input */
    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 characters */
    printf("%d\n", repl);  /* 2 replacement chars */
    for (size_t j = 0; j < o; j++) printf("%02x", out[j]);
    printf("\n"); /* 61efbfbd62efbfbd */
    return 0;
}
Output
4
2
61efbfbd62efbfbd

C++ C++26

C++26
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    const std::string bad = "a\xff" "b\xc3";
    // hand-rolled scrub: invalid/truncated lead bytes become 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;
}
Output
4
2
61efbfbd62efbfbd

C# v11.0.100

v11.0.100
byte[] bad = { 0x61, 0xff, 0x62, 0xc3 };
// .NET's UTF-8 decoder replaces malformed bytes with U+FFFD by default:
// GetString IS the 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
Output
4
2
61efbfbd62efbfbd

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	bad := "a\xffb\xc3"
	// strings.ToValidUTF8: every ill-formed byte run becomes the replacement
	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: clean UTF-8 now
}
Output
4
2
61efbfbd62efbfbd
true

Java v27.0.1

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)      // the errors='replace' analog
            .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
    }
}
Output
4
2
61efbfbd62efbfbd

JavaScript v26.13.1

v26.13.1
const bad = new Uint8Array([0x61, 0xff, 0x62, 0xc3]);
// fatal:false (default) replaces ill-formed bytes with U+FFFD;
// fatal:true would THROW instead - the strict counterpart
const dec = new TextDecoder("utf-8", { fatal: false });
const fixed = dec.decode(bad);
console.log(fixed.length);                          // 4 (code units; U+FFFD is 1)
console.log((fixed.match(/\uFFFD/g) || []).length); // 2
console.log(Buffer.from(fixed, "utf-8").toString("hex")); // 61efbfbd62efbfbd
Output
4
2
61efbfbd62efbfbd

PHP v8.6.0

v8.6.0
// mb_scrub: the same encoding round trip replaces ill-formed bytes.
// The substitute defaults to '?' - set U+FFFD for the standard cleaning mark:
mb_substitute_character(0xFFFD);
$bad = "a\xffb\xc3"; // \xc3 opens a 2-byte sequence and stops short: truncated
$fixed = mb_scrub($bad, 'UTF-8');
var_dump(mb_strlen($fixed));                    // 4 characters now
var_dump(mb_substr_count($fixed, "\u{FFFD}")); // 2 replacement marks
var_dump(bin2hex($fixed));                      // 61efbfbd62efbfbd: see what survived
var_dump(mb_check_encoding($fixed, 'UTF-8'));   // true: clean UTF-8, safe to process
Output
int(4)
int(2)
string(16) "61efbfbd62efbfbd"
bool(true)

Python v3.15.2

v3.15.2
bad = b"a\xffb\xc3"
# errors='replace' IS Python's scrub: every ill-formed byte -> U+FFFD.
# The strict counterpart is errors='strict' (raises) - PHP has no raise mode
fixed = bad.decode("utf-8", errors="replace")
print(len(fixed))                 # 4
print(fixed.count("\ufffd"))      # 2
print(fixed.encode("utf-8").hex()) # 61efbfbd62efbfbd
Output
4
2
61efbfbd62efbfbd

Rust v1.99.1

v1.99.1
fn main() {
    let bad: Vec<u8> = vec![0x61, 0xff, 0x62, 0xc3];
    // from_utf8_lossy IS the scrub: every ill-formed byte run -> U+FFFD
    let fixed = String::from_utf8_lossy(&bad); // Cow: borrowed when already valid
    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
}
Output
4
2
61efbfbd62efbfbd

TypeScript v26.13.1

v26.13.1
const bad = new Uint8Array([0x61, 0xff, 0x62, 0xc3]);
// fatal:false (default) replaces ill-formed bytes with 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
Output
4
2
61efbfbd62efbfbd

Language differences

C: no standard decoder - hand-roll it (example: ASCII passes through, invalid bytes become the three U+FFFD bytes); full correctness needs a UTF-8 grammar state machine, and the example is simplified for the demo bytes; glib's g_utf8_make_valid is the ready-made library route.

C++: hand-written as in C (std::string plus manual replacement in the example); there is no standard lossy-decode API - std::wstring_convert is deprecated, and real projects use ICU or a hand-written state machine.

C#: Encoding.UTF8.GetString ships with replacement fallback by default (no fatal switch) - GetString IS the scrub; for explicit control customize EncoderFallback/DecoderFallback; no strict variant exists (a prior GetByteCount-style check is the only route).

Go: strings.ToValidUTF8(s, repl) is the most direct counterpart - the replacement is your choice (U+FFFD in the example); each RUN of ill-formed bytes collapses into ONE replacement; utf8.ValidString verifies the result after cleaning.

Java: CharsetDecoder's three actions - REPLACE (the example, equal to errors='replace'), IGNORE, REPORT (throws, equal to strict); PHP has no raising mode, Java does.

JavaScript: TextDecoder with fatal:false (default) is the scrub - fatal:true throws TypeError, so the strict mode is builtin; the replacement is fixed at U+FFFD and not changeable (WHATWG encoding standard).

PHP: mb_scrub (7.2+) = one conversion into the same encoding, replacing ill-formed bytes with the substitute; the substitute defaults to ? (0x3F), NOT U+FFFD - the example sets mb_substitute_character(0xFFFD) first to scrub into U+FFFD (0xEFBFBD); only replacement mode exists, no strict raising variant; in data cleaning: scrub untrusted input (uploads, third-party APIs) before handing it to UTF-8-sensitive downstream.

Python: bytes.decode(errors='replace') is the builtin scrub with the replacement fixed at U+FFFD; the errors family - strict (raise), ignore (drop), replace (substitute), backslashreplace and more - offers the richest behavior control.

Rust: String::from_utf8_lossy is the builtin scrub (returning Cow<str> - zero-copy borrow when the bytes are already valid); the strict version String::from_utf8 returns a Result; the replacement is fixed at U+FFFD; each ill-formed run collapses into one replacement (WHATWG style).

TypeScript: same as JavaScript.