Friday, November 14, 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
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS