7

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      ";

4 Answers 4

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Instead of * quantifier, you could use + quantifier to avoid replace nothing by nothing.
10

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 :

2 Comments

Heh, I'd like to know too, +1 to set things right with the universe.
+1 since this answer is maybe less fascinating, but the right one!
4

You can use rtrim

Comments

1

You can use trim() to do this:

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

2 Comments

Sorry... missed "AT THE END". As the others pointed out... rtrim()
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.