How to remove all non-printable characters in a string in PHP?

Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to take only those char which occur in range(32-127). This task is done by only differents type regex expression.

Example:

Input: str = "\n\nGeeks \n\n\n\tfor Geeks\n\t"
Output: Geeks for Geeks

Note: Newline (\n) and tab (\t) are commands not printable character.



Method 1: Using general regular expression: There are many regex available. The best solution is to strip all non-ASCII characters from the input string, that can be done with this preg_replace.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?PHP
// PHP program to remove all non-printable
// character from string
  
// String with non printable characters
$str = "Geeks šžfor ÂGee\tks\n";
  
// Using preg_replace method to remove all 
// non-printable character from string
$str = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $str);
  
// Display the modify string
echo($str);
  
?>

chevron_right


Output:

Geeks for Geeks

Method 2: Use the ‘print’ regex: Other possible solution is to use the print regular expression. The [:print:] regular expression stands for “any printable character”.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

   
<?PHP
// PHP program to remove all non-printable
// character from string
  
// String with non printable char
$str = "Geeks šžfor ÂGee\tks\n";
  
// Using preg_replace method to remove all 
// non-printable character from string
$str = preg_replace('/[[:^print:]]/', '', $str);
  
// Display modify string
echo($str);
  
?>

chevron_right


Output:

Geeks for Geeks


My Personal Notes arrow_drop_up

Just another competitive programmer and hard worker

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.