This is hard to acheive when it comes to unicode characters. Even valid unicode characters (there are a ton of it) might not being printable because the current font contains no letter definitions for that character. Meaning a German unicode font might not contain all valid Chinese characters for example.
If you just care about ascii, you can use ctype_print()
to check if a character is printable or not.
Example:
// test string contains printable and non printable characters
$string = "\x12\x12hello\x10world\x03";
$allowed = array("\x10", /* , ... */);
// iterate through string
for($i=0; $i < strlen($string); $i++) {
// check if current char is printable
if(ctype_print($string[$i]) || in_array($string[$i], $allowed)) {
print $string[$i];
} else {
// use printf and ord to print the hex value if
// it is a non printable character
printf("\\x%02X", ord($string[$i]));
}
}
Output:
\x12\x12hello
world\x03