Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 different 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: 

php




<?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);
 
?>


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: 

php




<?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);
 
?>


Output:

Geeks for Geeks


Last Updated : 03 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads