Stripping whitespace in PHP

Here's a simple way to strip all whitespace from a string in PHP, which is useful for properly trimming any user input:

function realtrim($mixed) {
   if (is_array($mixed)) {
      return array_map('realtrim', $mixed);
   }
   if (strlen($mixed) > 0) {
      $mixed = trim(preg_replace('/[\s]+/', ' ', $mixed));
   }
   return $mixed;
}

The above function will strip all multiple spaces, tabs, line feeds and carriage returns. It also has the capability to accept an array as input, making it particularly suitable for web forms.

Due to the large volume of spam, comments are disabled. If you have anything relevant to say, you can leave a , or contact me directly.

About the author

Ivan's mugshotI'm Ivan Lutrov and I'm the owner of Lutrov Interactive. I have 25 years of experience producing interactive work and I create cost effective business websites that are simple, engaging and easy to use. I practice what I preach and I say what I really think, even if it's sometimes not what you want to hear. Subscribe to the Lutrov Interactive feed via RSS and follow me on Twitter.