Skip to content
Advertisement

How to remove spaces before and after a string?

I have two words spirited by space of course, and a lot of spaces before and after, what I need to do is to remove the before and after spaces without the in between once.

How can I remove the spaces before and after it?

Advertisement

Answer

You don’t need regex for that, use trim():

$words = '      my words     ';
$words = trim($words);
var_dump($words);
// string(8) "my words"

This function returns a string with whitespace stripped from the beginning and end of str.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement