Friday, October 10, 2025
HomeLanguagesHow to remove control characters from PHP string ?

How to remove control characters from PHP string ?

Given a string that contains control characters. The task is to remove all control characters from a string. In ASCII, all characters having a value below 32 come under this category. Some of the control characters are given below:

S.NO ASCII VALUE Name Symbol
1. 0 null (NUL) “\0”
2. 9 horizontal tab(HT) “\t”
3. 10 line feed(LF) “\n”
4. 11 vertical tab(VT) “\v”
5. 27 escape(ESC) “\e”

Example:

Input: str = "\0\eGeeks\t\e\tfor\v\vGeeks"
Output: neveropen

In this article, we will remove control characters from the PHP string by using two different methods.

  • Using General Regular Expression:
  • Using ‘cntrl’ Regex:

Using General Regular Expression: There are many regular expressions that can be used to remove all Characters having ASCII value below 32. Here, we will be using preg_replace() method.

Note: The ereg_replace() method is removed from PHP >= 7, so here we will be using preg_replace() method.

  • Program:




    <?PHP 
      
    // PHP program to remove all control 
    // characters from string 
        
    // String with control characters 
    $str = "\eGeeks\t\tfor\v\vGeeks\n"
        
    // Using preg_replace method to remove all  
    // control characters from string 
    $str = preg_replace('/[\x00-\x1F\x7F]/', '', $str); 
        
    // Display the modify string 
    echo($str); 
        
    ?> 

    
    
  • Output:
    neveropen

Using ‘cntrl’ Regex: This can also be used to remove all control characters. And [:cntrl:] stands for all control character.

  • Program:




    <?PHP 
      
    // PHP program to remove all control 
    // characters from string 
        
    // String with control characters 
    $str = "\eGeeks\t\tfor\vGeeks\n"
        
    // Using preg_replace method to remove all  
    // control characters from string 
    $str = preg_replace('/[[:cntrl:]]/', '', $str); 
        
    // Display the modify string 
    echo($str); 
        
    ?> 

    
    
  • Output:
    neveropen
RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS