PHP: Strip or Trim Extra Whitespaces Inside a String

There are raw strings that contain extraly unwanted whitespaces (tabs, spaces, new lines) that you want to get rid of so as to form a normalized string that has only a single spaces between words and sentences. For instance, you may want to transform this string:

Morning   is here,   sunshine
   is here.    Morning is    here.

Into this:

Morning is here, sunshine is here. Morning is here.

How to achieve this in PHP?

Just use this function:

function purge_inside_whitespaces($text) {
	while (preg_match('/\s{2}/', $text)) {
		$text = preg_replace('/\s{2}/', ' ', $text);
	}
	return $text;
}

Basically, it keeps scouring through the $text string passed to it and removes any continuous whitespaces and replace them with single spaces, until it can’t find any more continuous whitespaces.

Note you would need to apply trim() to get rid of any whitespaces in the beginning or at the end of the string, because if there are any there, a single space would still remain after applying purge_inside_whitespaces().

Scroll to Top