Remove undesired characters with trim_all() - PHP

Web-hosting business can now be started for just $19.95 with unlimited resources. Start your own.

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 a provided as second argument to
trim
, removes white-space characters as provided in this list.

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 characters-to-replace and characters-to-replace-with. With this function, you can:
  1. 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;
  2. remove all undesired characters;
  3. remove duplicates;
  4. replace multiple occurrences of characters with a character or string.
  1. function trim_all( $str , $what = NULL , $with = ' ' )
  2. {
  3.     if( $what === NULL )
  4.     {
  5.         //  Character      Decimal      Use
  6.         //  "\0"            0           Null Character
  7.         //  "\t"            9           Tab
  8.         //  "\n"           10           New line
  9.         //  "\x0B"         11           Vertical Tab
  10.         //  "\r"           13           New Line in Mac
  11.         //  " "            32           Space
  12.        
  13.         $what   = "\\x00-\\x20";    //all white-spaces and control chars
  14.     }
  15.    
  16.     return trim( preg_replace( "/[".$what."]+/" , $with , $str ) , $what );
  17. }
PHP Code

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

Example Use

  1. trim_all( $_POST['full_name'] );
PHP Code



  1. High Performance Hosting is now $3.96 a month
  2. Replace last occurance of a String - PHP
  3. How to validate ASCII Text - PHP
  4. Number-to-Word Conversion with PHP
  5. Insecure PHP Constants and Variables
  6. Implementing QuickSort in PHP


© 2012-2017 PageConfig.com - Scripts - Twitter