Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: remove extra space from a string using regex

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      ";
like image 583
Zebra Avatar asked Sep 21 '10 18:09

Zebra


2 Answers

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.

like image 142
codaddict Avatar answered Sep 19 '22 23:09

codaddict


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 :

  • trim()
  • ltrim()
like image 32
Colin Hebert Avatar answered Sep 20 '22 23:09

Colin Hebert