In PHP, we can use mb_check_encoding() to determine if a string is valid UTF-8. But that’s not a portable solution as it requires the mbstring extension to be compiled in and enabled. Additionally, it won’t tell us which character is invalid.
Is there a regular expression (or another other 100% portable method) that can match invalid UTF-8 bytes in a given string?
That way, those bytes can be replaced if needed (keeping the binary information, such as when building a test output XML file that includes binary data). So converting the characters to UTF-8 would lose information. So, we may want to convert:
"foo" . chr(128) . chr(255)
Into
"foo<128><255>"
So just "detecting" that the string is not good enough, we’d need to be able to detect which characters are invalid.
You can use this PCRE regular expression to check for byte sequences in a string that are not valid UTF-8. If the regex matches, the string contains invalid byte sequences. It’s 100% portable because it doesn’t rely on PCRE_UTF8 to be compiled in.
We can test it by creating a few variations of text:
etc…
In fact, since this matches invalid bytes, you could then use it in preg_replace to replace them away: