Note! This function only performs its work if the blog_charset is set to UTF-8. For all other values it returns the input text unchanged. Note! Unless requested, this returns an empty string if the input contains any sequences of invalid UTF-8. To replace invalid byte sequences, pass true as the optional $strip parameter. Consider using wp_scrub_utf8() instead which does not depend on the value of blog_charset. Example: // The blog_charset is latin1, so this returns the input unchanged.
$every_possible_input === wp_check_invalid_utf8( $every_possible_input );
// Valid strings come through unchanged.
'test' === wp_check_invalid_utf8( 'test' );
$invalid = "the byte xC0 is never allowed in a UTF-8 string.";
// Invalid strings are rejected outright.
'' === wp_check_invalid_utf8( $invalid );
// “Stripping” invalid sequences produces the replacement character instead.
"the byte \u{FFFD} is never allowed in a UTF-8 string." === wp_check_invalid_utf8( $invalid, true );
'the byte � is never allowed in a UTF-8 string.' === wp_check_invalid_utf8( $invalid, true );
Parameters
$textstring
String which is expected to be encoded as UTF-8 unless blog_charset is another encoding.
$stripbooloptional
Whether to replace invalid sequences of bytes with the Unicode replacement character (U+FFFD �). Default false returns an empty string for invalid UTF-8 inputs.Default: false
Return
string
The checked text.
Uses · 3
is_utf8_charset()Indicates if a given slug for a character set represents the UTF-8 text encoding. If not provided, examines the current blog's charset.
wp_is_valid_utf8()Determines if a given byte string represents a valid UTF-8 encoding.
wp_scrub_utf8()Replaces ill-formed UTF-8 byte sequences with the Unicode Replacement Character.
Used by · 6
_sanitize_text_fields()Internal helper function to sanitize a string from user input or from the database.
1127functionwp_check_invalid_utf8($text,$strip=false){1128$text=(string)$text;11291130if(0===strlen($text)){1131return'';1132}11331134// Store the site charset as a static to avoid multiple calls to get_option().1135static$is_utf8=null;1136if(!isset($is_utf8)){1137$is_utf8=is_utf8_charset();1138}11391140if(!$is_utf8||wp_is_valid_utf8($text)){1141return$text;1142}11431144return$strip1145?wp_scrub_utf8($text)1146:'';1147}
History
Introduced in 2.8.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
6.9.0
Stripping replaces invalid byte sequences with the Unicode replacement character U+FFFD (�).from the docblock
2.8.0
Introduced.from the docblock
About this page
Parsed data
Generated from the wordpress-develop 7.1.0 tag, from src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.