Thursday, December 18, 2025
HomeLanguagesPHP mb_detect_encoding() Function

PHP mb_detect_encoding() Function

The mb_detect_encoding() is an inbuilt function in PHP that is used to detect the encoding of the string. 

Syntax:

string|false mb_detect_encoding(
    string $string, 
    array|string|null $encodings = null, 
    bool $strict = false
)

Parameters: This function accepts three parameters that are described below.

  • $string: The string for which the encoding needs to be detected.
  • $encoding:  A comma-separated list of encodings to be checked. If not specified, a list of popular encodings is used.
  • $strict:  A boolean value indicating whether to use strict detection or not. If set to “true”, only encodings that are super-sets of the input string’s encoding are returned.

Return Values: This function returns detecting encoding of the input string, if no encoded is detected, it will return “false”.

Example 1: The following program demonstrates the mb_detect_encoding() function.

PHP




<?php
$string = "Hello world!";
$encoding = mb_detect_encoding($string);
echo "The string '$string' is encoded in '$encoding'.";
?>


Output:

The string 'Hello world!' is encoded in 'ASCII'.  

Example 2: The following program demonstrates the mb_detect_encoding() function.

PHP




<?php
$string = "This is an English sentence.";
$encoding = mb_detect_encoding($string);
if ($encoding === 'UTF-8') {
    echo "The string '$string' is encoded in UTF-8.";
} else {
    echo "The string '$string' is not encoded in UTF-8.";
}
?>


Output:

The string 'This is an English sentence.' is not encoded in UTF-8.   

Reference: https://www.php.net/manual/en/function.mb-detect-encoding.php

RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11957 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12034 POSTS0 COMMENTS
Shaida Kate Naidoo
6957 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6909 POSTS0 COMMENTS
Umr Jansen
6888 POSTS0 COMMENTS