How to Strip Whitespaces in PHP

Unsightly whitespace can seriously mess up some text. Although most of the browsers nowadays ignore whitespace, if the text is inside a form element such as a <textarea> or inside <pre> tag.


The code we are sharing below makes use of built-in PHP regular expression feature. First let me show the code, then I’ll explain the code how it is working.

[code type=”php”]
//Function to remove whitespace from text
function removeWhiteSpace($str)
return preg_replace(‘/\s+/’, ‘ ‘, $str);

//Call the function
$str = “Your Text Here…”;
echo removeWhiteSpace($str);

What the above code does is search for the text within the two forward slash characters ,/, and then replaces any it finds with a single space.

\s+ means find any part of white space that is one ore more characters in length. + indicates that the preceding character should appear one or more times in search and s means whitespace character.

In the end, actual string passed to the PHP preg_replace() function is modified and then returned to the calling code. I hope you will find this code snippet useful.

Leave a Comment