Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Validate UTF8 Strings

<?php

$string = 'a'.chr(245);

var_dump( mb_check_encoding($string) );

// iconv() is undefined here
//var_dump(@iconv('UTF-8', 'UTF-8', $string) !== false);

if (preg_match('##u', $string)) {
    print "OK
";
} else {
    print "KO
";
}

var_dump( json_encode($string) );

For an integer, PHP offers is_int(). But for UTF8, there is no is_valid_utf8().

The adapted function is mb_check_encoding(), which can also check for other encoding than UTF8.

Then, there is also preg_match(), with the u option, to tell it to use unicode. This is a case of a useful empty regex.

Then, it is possible to convert a string from UTF8 to UTF8 with iconv(), which yields error in case of invalid string, but leaves the string intact.

Finally, you can misuse json_encode(), which enforces the UTF8 valid string from the JSON format. There is no warning, but it returns false in case of error.

See Also

PHP Features

Last updated: 09 November 2026