phpstring

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?


Solution

  • 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.
      Since PHP 8.4 mb_trim() is also available.

    2. If you want to remove only excess space characters (" ") within a string, consider the following preg_replace:

       $foo = preg_replace('/ +/', ' ', $foo);
      
    3. If you are dealing with extra whitespace within a string, consider using preg_replace to replace multiple whitespace characters ([\r\n\t\f\v ]) with a single space character (" "). Example:

       $foo = preg_replace('/\s+/', ' ', $foo);
      
    4. In case you want to deal with each whitespace sequence separately (so two linefeeds won't become a single space):

       $foo = preg_replace("/( |\r\n|\n|\r|\v|\t)\\1+/", "$1", $foo)
      

      (courtesy this answer)