Remove undesired characters with trim_all() – PHP

This function was inspired from PHP’s built-in function trim() that removes undesired characters from the start and end of a string, and in case no such characters are provided as second argument to the function, it removes white-space characters from both ends of the string.

So, what does trim_all() do?

trim_all() was intended to remove all instances of white-spaces from both ends of the string, as well as remove duplicate white-space characters inside the string. But, later on, I made it a general purpose function to do a little more than just white-space trimming and cleaning, and made it to accept custom characters to replace and to replace with in the string. With this function, you can:

  • normalize white-spaces, so that all multiple \r, \n, \t, \r\n, \0, 0x0b, 0x20 and all control characters can be replaced with a single space, and also trimed from both ends of the string;
  • remove all undesired characters;
  • remove duplicates of any character;
  • replace multiple occurrences of characters with a character or string.
function trim_all( $str , $what = NULL , $with = ' ' )
{
    if( $what === NULL )
    {
        //  Character      Decimal      Use
        //  "\0"            0           Null Character
        //  "\t"            9           Tab
        //  "\n"           10           New line
        //  "\x0B"         11           Vertical Tab
        //  "\r"           13           New Line in Mac
        //  " "            32           Space
       
        $what   = "\\x00-\\x20";    //all white-spaces and control chars
    }
   
    return trim( preg_replace( "/[".$what."]+/" , $with , $str ) , $what );
}

This function can be helpful when you want to remove unwanted characters from users’ input. Here is how to use it.

Example Use

echo trim_all( $_POST['full_name'] );