Remove Excess Whitespaces in a String in PHP

In this tutorial, we will look at the different ways to remove excess whitespaces in a string in PHP

 

From the Start and End of a String

To remove all excess white spaces from both the beginning and end of a string, use the PHP trim() utility. trim() does not modify the original string so the result will need to be assigned to a variable.

 

$str = '   some text here    ';

$str = trim($str);

dd($str);
"some text here"

 

From the Start Only

To remove excess whitespaces from the start of a string only, use the PHP ltrim() utility.

 

$str = '   some text here    ';

$str = ltrim($str);

dd($str);
"some text here    "

 

From the End Only

To remove excess whitespaces from the end of a string only, use the PHP rtrim() utility.

 

$str = '   some text here    ';

$str = rtrim($str);

dd($str);
"   some text here"

 

 

Remove all Excess Whitespaces

To remove all excess whitespaces from anywhere within a string we can use some regex in a preg_replace() function in conjunction with trim().

 

$str = '   some text    here    ';

$str = trim(preg_replace('/\s+/',' ', $str));

dd($str);
"some text here"

 

The preg_replace() part matches repeating whitespaces and replaces them with a single whitespace. Then trim() removes excess whitespace characters from the start and end of the string.

 

Remove all Whitespaces in a String

We can use str_replace() to look for any whitespaces in a string and replace them with nothing.

 

$str = '   some text    here    ';

$str = str_replace(' ', '', $str);

dd($str);
"sometexthere"

 

Conclusion

You now know how to remove unwanted whitespaces from a string in PHP in a variety of different ways.

string