Simplify your business
Monday, 13 October 2008 10:48 pm

Stripping whitespace in PHP

Wednesday, 20 September 2006  

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.

Posted in PHP, Programming, Tips by Ivan
Blinklist icon Del.iocio.us icon Furl icon Reddit icon Technorati icon Yahoo! icon

Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.