How to remove all non printable characters in a string?

To remove all non-printable characters in a string in PHP, you can use the preg_replace function with a regular expression pattern that matches non-printable characters.

Here's an example of how you can use preg_replace to remove all non-printable characters from a string:


$string = "This is a \r\nstring with\tnon-printable\x0Bcharacters.";

$string = preg_replace('/[\x00-\x1F\x80-\xFF]/', ' ', $string);

$string = preg_replace('/\s+/', ' ', $string); // add this line to replace multiple spaces with a single space

echo $string; // Outputs: "This is a string with non-printable characters."

Watch a course Learn object oriented PHP

The regular expression pattern /[\x00-\x1F\x80-\xFF]/ matches any character that has a ASCII code value between 0 and 31 (inclusive), or between 128 and 255 (inclusive). These are the ASCII code values for non-printable characters.

The preg_replace function replaces all matches of the pattern with an empty string, effectively removing the non-printable characters from the string.