


In such cases, there will be one space character present on both sides even after using preg_replace(). The only problem now is that the main string might contain multiple whitespace characters at both ends. In the above example, the + after \s means that you want to replace one or more whitespace characters with a single space. $stripped = preg_replace('/\s+/', ' ', $sentence) 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. 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. $stripped = preg_replace('/\s/', '', $sentence) Replace multiple whitespace characters with a single space The special \s character in a regular expression is used to represent all whitespace characters that you removed by trim(), ltrim() and rtrim(). In such cases, using the str_replace() function won’t cut it. The whitespace can consist of more than just space characters.

$stripped = str_replace(' ', '', $sentence) 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. The trimming function will be ineffective against it. 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. These functions will remove the following whitespace characters: 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(). Remove whitespace from the beginning or end of a String Similarly, you might be planning on stripping all the whitespace from either the left or the right end of a string. 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. Many times, the strings have extra spaces that need to be removed.
