Friday, October 24, 2025
HomeLanguagesHow to remove all non-printable characters in a string in PHP?

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 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
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS