PHP mb_check_encoding() Function

Definition
In PHP, mb_check_encoding() checks whether every byte of a string is valid in a given character encoding.
It is the quick way to test user input before you store or process it.
Syntax
Call mb_check_encoding() with the values you need. Start with this line.
$valid = mb_check_encoding($text, "UTF-8");
| Call | What it does |
|---|
mb_check_encoding("café", "UTF-8") | Returns true. |
mb_check_encoding("caf\xE9", "UTF-8") | Returns false. |
If you leave out the encoding, the internal encoding is used. It is UTF-8 on most servers.
Library declarations
mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool
Parameters
| Parameter | Description |
|---|
| value | Required in practice. The string (or array of strings) to check. |
| encoding | Optional. The encoding to check against. Default is the internal encoding. |
Return Value
| Return Value | Description |
|---|
| bool | true if the value is valid in that encoding, false if not. |
PHP Examples
Example 1 — Check a UTF-8 String
A normal accented word is valid UTF-8.
<?php
var_dump(mb_check_encoding("café", "UTF-8"));
How It Works
- Pass the text. It is saved as UTF-8.
- Pass the encoding name. Here it is
UTF-8. - Get
true. Every byte is valid. - Use
var_dump() to see the type.
Example 2 — Spot an Invalid String
A single Latin-1 byte is not valid UTF-8.
<?php
$text = "caf\xE9";
var_dump(mb_check_encoding($text, "UTF-8"));
var_dump(mb_check_encoding($text, "ISO-8859-1"));
How It Works
- Use a Latin-1 byte.
\xE9 is é in ISO-8859-1. - Check it as UTF-8. The byte stands alone, so it is invalid.
- Check it as ISO-8859-1. Every byte is valid there.
- Use the result to choose the right conversion.
Frequently Asked Questions
mb_check_encoding() tells you whether a string is valid in a given character encoding.
mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool.
Yes. Since PHP 7.2 you can pass an array and every key and value is checked.
PHP checks against the internal encoding, which is usually UTF-8.
Convert it from the right source encoding with mb_convert_encoding(), for example from ISO-8859-1 to UTF-8.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful