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);
[/code]

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.

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment