PHP: remove excess space from string using regex

How to remove extra spaces at the end of a line using regex (preg_replace)?

$string = "some random text with extra spaces at the end "; 
+6
string php regex whitespace
source share
5 answers

There is no need for a regular expression, and you can use rtrim to make it cleaner and faster:

 $str = rtrim($str); 

But if you want to use a regex-based solution, you can use:

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

Regular expression used /\s*$/

  • \s for any char space that includes space.
  • * - quantifier for zero or more
  • $ is the ultimate anchor

We basically replace the trailing space characters with nothing ( '' ), effectively removing them.

+16
source share

Here you do not need a regular expression, you can use the rtrim () function.

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

Code on the idea


See also:

+9
source share

You can use rtrim

+3
source share

You can use trim () to do this:

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

+1
source share

you can use php cropping and preg_replace for this.

to see the full example, click this link http://akhleshit.blogspot.com/2013/04/remove-extra-spaces-from-string-in-php.html

0
source share

All Articles