Skip to content
Related Articles

Related Articles

How to remove all non-printable characters in a string in PHP?
  • Difficulty Level : Hard
  • Last Updated : 07 May, 2019

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:






<?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 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
My Personal Notes arrow_drop_up
Recommended Articles
Page :