How To Remove Whitespace Characters in a string in PHP - trim() Function

PHP String Functions

Many times, the strings have extra spaces that need to be removed. For example, you might want to replace multiple spaces with a single space or you might want to get rid of all the whitespace in a string. Similarly, you might be planning on stripping all the whitespace from either the left or the right end of a string.

Remove whitespace from the beginning or end of a String

If you want to remove whitespace only from the beginning of a string, you should use the ltrim() function in PHP. If you want to remove whitespace only from the end of a string, you should use the rtrim() function in PHP. If you want to remove whitespace from both ends of a string, you should use the trim() function instead of using both ltrim() and rtrim().

These functions will remove the following whitespace characters: 

  1. " " (an ordinary space)
  2. "\t" (a tab)
  3. "\n" (a new line)
  4. "\r" (a carriage return)
  5. "\0" (the NUL-byte)
  6. "\x0B" (a vertical tab)

Remove all the whitespace in a String

Some times, the strings you are working with will have unwanted whitespace in the middle and in the beginning as well as in the end. The trimming function will be ineffective against it.

If you just want to remove all the whitespace characters irrespective of where they occur in the string, you should use str_replace() to replace all their occurrences with a blank string.

$stripped = str_replace(' ', '', $sentence);

The whitespace can consist of more than just space characters. In such cases, using the str_replace() function won’t cut it. The special \s character in a regular expression is used to represent all whitespace characters that you removed by trim(), ltrim() and rtrim().

$stripped = preg_replace('/\s/', '', $sentence);

Replace multiple whitespace characters with a single space

Most of the times when you decide to remove extra whitespace characters from a string, you would want to replace two or more of them with a single space character. This is different than removing all the spaces so you will have to make small changes in the regular expression and the preg_replace() function.

$stripped = preg_replace('/\s+/', ' ', $sentence);

In the above example, the + after \s means that you want to replace one or more whitespace characters with a single space. The only problem now is that the main string might contain multiple whitespace characters at both ends. In such cases, there will be one space character present on both sides even after using preg_replace(). The solution here is to use trim() on the resulting string.

$stripped = trim(preg_replace('/\s+/', ' ', $sentence));
Star ActiveStar ActiveStar ActiveStar ActiveStar Inactive