Era Host hosting
EraHost – Free Domain, Cheap Hosting!
Client Area
Support 24/7
Menu

mb_detect_encoding in PHP — Detect Character Encoding

4 min read
07.01.2026

Syntax of mb_detect_encoding

mb_detect_encoding(string $string, array|string $encodings = null, bool $strict = false): string|false
  • $string ? The string to check for character encoding.
  • $encodings (optional) ? A list of possible encodings to check against. Can be a comma-separated string or an array (e.g., 'UTF-8, ISO-8859-1' or ['UTF-8', 'ISO-8859-1']). If null, it uses mb_detect_order().
  • $strict (optional) ? If true, it performs stricter encoding detection (slower but more accurate).

Returns: The detected encoding name (e.g., "UTF-8", "ISO-8859-1") or false if detection fails.

mb_detect_encoding PHP Character Encoding
mb_detect_encoding — heuristic; reliable only when the list is small.

For related PHP-string / encoding topics, see Setting mbstring.func_overload for Bitrix and DB_COLLATE in WordPress.

Detect Encoding of a String

Basic Detection Example

Detect the encoding of a string with Russian text:

<?php
$string = "??????, ???!"; // Russian text
$encoding = mb_detect_encoding($string, "UTF-8, ISO-8859-1, Windows-1251");

echo "Detected encoding: " . ($encoding ?: "Unknown");
?>

Output: Detected encoding: UTF-8

Detect Encoding from Multiple Encodings

You can specify a prioritized list of encodings to check. The function returns the first match from your list.

Checking Against Specific Encodings

<?php
$text = "Hello World";  // Text with accented characters
$encodings = ["UTF-8", "ISO-8859-1", "Windows-1252"];
$detected = mb_detect_encoding($text, $encodings, true); // Strict mode

echo $detected ? "Encoding: $detected" : "Encoding not detected";
?>

Possible Output: Encoding: UTF-8

Important: The $encodings parameter order matters! PHP checks encodings in the order you provide. Always list the most likely encoding first (usually UTF-8 for modern applications).
Linux VDS
High performance for your projects
  • Root access and flexible setup
  • Control panel
  • NVMe disks
  • DDR5
Linux VDS

Convert Encoding After Detection

Once you've detected the encoding, you can convert the string to your desired encoding (usually UTF-8) using mb_convert_encoding().

Detect and Convert to UTF-8

<?php
// Simulate reading content that might be in a different encoding
$string = file_get_contents("legacy_data.txt");

// Detect the current encoding
$encoding = mb_detect_encoding($string, ["UTF-8", "ISO-8859-1", "Windows-1252"]);

if ($encoding && $encoding !== "UTF-8") {
    // Convert to UTF-8
    $string = mb_convert_encoding($string, "UTF-8", $encoding);
    echo "Converted from $encoding to UTF-8.";
} else {
    echo "String is already UTF-8 or encoding detection failed.";
}

// Now $string is (hopefully) in UTF-8
echo "Processed string: " . $string;
?>

Common Use Cases

  • Fixing character encoding issues in databases ? When importing data from legacy systems.
  • Handling multi-language text input ? From web forms or APIs that don't specify encoding.
  • Converting legacy encoding ? e.g., Windows-1252 > UTF-8 for modern web applications.
  • Processing uploaded files ? CSV, text files that could be in various encodings.
  • Validating user input ? Ensuring text is in the expected encoding before processing.

Handling Unknown Encodings

Sometimes mb_detect_encoding() returns false or an incorrect result. Here are workarounds:

Fallback Strategies

1. Force conversion with "auto" detection:

$string = mb_convert_encoding($string, "UTF-8", "auto");

2. Use iconv() with IGNORE option to handle invalid characters:

$detected = mb_detect_encoding($string, mb_list_encodings(), true);
if ($detected) {
    $string = iconv($detected, "UTF-8//IGNORE", $string);
}

3. Check if string is valid UTF-8 before processing:

if (!mb_check_encoding($string, 'UTF-8')) {
    // Not UTF-8, try to detect and convert
    $string = mb_convert_encoding($string, 'UTF-8', 'auto');
}

Summary of mb_detect_encoding()

Feature Description
Detects text encoding Returns encoding name like "UTF-8", "ISO-8859-1", or false
Supports multiple encodings Specify prioritized list: ["UTF-8", "ISO-8859-1"]
Strict mode available More accurate detection with true (slower)
Handles multibyte characters Essential for Unicode (UTF-8) and legacy encodings
Works with mb_convert_encoding() Detect then convert: mb_convert_encoding($str, "UTF-8", $detected)
Requires mbstring extension Enable via extension=mbstring in php.ini
Best Practice: For web applications, aim to normalize all text to UTF-8 as early as possible in your processing pipeline. Use mb_detect_encoding() as a tool to identify and convert non-UTF-8 text.

Now you can effectively detect and fix character encoding issues in your PHP applications!

Frequently asked questions
Strict mode (third arg `true`) returns `false` if none of the candidates match perfectly — strings that look like ambiguous Latin-1/UTF-8 are common false-negative cases. Non-strict mode (default) returns the first candidate that doesn't explicitly fail, which is misleading. For reliable detection, always use strict mode and a short, ordered list of expected encodings.
Yes — significantly. The function returns the first match in order. If you list `['ASCII', 'UTF-8', 'Windows-1252']`, a UTF-8 string that starts with ASCII bytes returns 'ASCII' — wrong. Put the most specific / most-restrictive encodings first: `['UTF-8', 'Windows-1251', 'ISO-8859-1']`. UTF-8 is generally safe at the top because non-UTF-8 bytes fail validation.
Test for UTF-8 first; if that fails, test Windows-1251 and KOI8-R. UTF-8 validation is reliable (multi-byte sequences must follow strict rules). Cyrillic Windows-1251 vs KOI8-R cannot be distinguished perfectly by bytes alone — both use the same 0x80-0xFF range. If precision matters, check against a dictionary or fall back to letting the user pick.
mb_detect_encoding scans the entire string. For large files, sample the first ~64KB and detect on that — modern encodings are consistent throughout. Or use `iconv` with `//IGNORE` to test conversion success: convert to UTF-8 and check if length changed. Less elegant, sometimes faster for many small files (avoids per-call mbstring overhead).
Related articles
PHP mb_detect_encoding() — Supporting Multiple Encodings
Fixing ERR_INVALID_RESPONSE in PHP — System Administrator's Guide
550-5.7.1 "Likely Unsolicited Mail" Error