mb_detect_encoding()
mb_detect_encoding() — Detect character encoding.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Detects the most likely character encoding for string string from a list of candidates.
Signature
mb_detect_encoding(string $string, array|string|null $encodings = null, bool $strict = false): string|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $string | string | The string being inspected. |
| $encodings | array|string|null | A list of character encodings to try. The list may be specified as an array of strings, or a single string separated by commas. |
| $strict | bool | Controls the behaviour when string is not valid in any of the listed encodings. If strict is set to false, the closest matching encoding will be returned; if strict is set to true, false will be returned. |
Return value
The detected character encoding, or false if the string is not valid in any of the listed encodings.
Example
A runnable snippet:
$str = "\x95\xB6\x8E\x9A\x83\x52\x81\x5B\x83\x68"; // Detect character encoding with current detect_order var_dump(mb_detect_encoding($str)); // "auto" is expanded according to mbstring.language var_dump(mb_detect_encoding($str, "auto")); // Specify "encodings" parameter by list separated by comma var_dump(mb_detect_encoding($str, "JIS, eucjp-win, sjis-win")); // Use array to specify "encodings" parameter $encodings = [ "ASCII", "JIS", "EUC-JP" ]; var_dump(mb_detect_encoding($str, $encodings));
Output:
string(5) "ASCII" string(5) "ASCII" string(8) "SJIS-win" string(5) "ASCII"
Changelog
| Version | Change |
|---|---|
| 8.2.0 | mb_detect_encoding() will no longer return the following non text encodings: "Base64", "QPrint", "UUencode", "HTML entities", "7 bit" and "8 bit". |
See also
All PHP 8.5 built-in functions
Reference card built from the PHP manual page mb_detect_encoding() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.