Remove excess whitespace from within a string


I receive a string from a database query, then I remove all HTML tags, carriage returns and newlines before I put it in a CSV file. Only thing is, I can't find a way to remove the excess white space from between the strings.

What would be the best way to remove the inner whitespace characters?

9/11/2013 10:16:45 AM

Accepted Answer

Not sure exactly what you want but here are two situations:

  1. If you are just dealing with excess whitespace on the beginning or end of the string you can use trim(), ltrim() or rtrim() to remove it.

  2. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " ".


$foo = preg_replace('/\s+/', ' ', $foo);
7/30/2014 4:26:16 PM

$str = str_replace(' ','',$str);

Or, replace with underscore, & nbsp; etc etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow