views:

74

answers:

4

How do I remove extra spaces at the end of a string using regex (preg_replace)?

$string = "some random text with extra spaces at the end      ";
+3  A: 

You can use rtrim

Gazler
@Gazler, thank you!
dany
+6  A: 

You don't really need regex here, you can use the rtrim() function.

$string = "some random text with extra spaces at the end      ";
$string = rtrim($string);

Code on ideone


See also :

Colin Hebert
Downvoter, any reason ?
Colin Hebert
Heh, I'd like to know too, +1 to set things right with the universe.
Gazler
@Colin Hebert, Thank you! I did not downvote just so you know
dany
+11  A: 

There is no need of regex here and you can use rtrim for it, its cleaner and faster:

$str = rtrim($str);

But if you want a regex based solution you can use:

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

The regex used is /\s*$/

  • \s is short for any white space char, which includes space.
  • * is the quantifier for zero or more
  • $ is the end anchor

Basically we replace trailing whitespace characters with nothing (''), effectively deleting them.

codaddict
Instead of `*` quantifier, you could use `+` quantifier to avoid replace nothing by nothing.
M42
@codaddict, thank you very much!!! the character info is much appreciated
dany
@M42, thank you!
dany
+1  A: 

You can use trim() to do this:

http://php.net/manual/en/function.trim.php

Don
Sorry... missed "AT THE END". As the others pointed out... rtrim()
Don
@Don you can edit your answer.
LarsH
@Don, thank you!
dany
@LarsH, Didn't want to edit it to be the same as the other in case the trim() option may work for future searchers, but point taken...thx
Don