26

I am pretty new to regular expressions. I need to clean up a search string from spaces at the beginning and the end. Example: " search string " Result: "search string"

I have a pattern that works as a javascript solution but I cant get it to work on PHP using preg_replace:

Javascript patern that works:

/^[\s]*(.*?)[\s]*$/ig

My example:

$string = preg_replace( '/^[\s]*(.*?)[\s]*$/si', '', " search string " );
print $string; //returns nothing

On parse it tells me that g is not recognized so I had to remove it and change the ig to si.

Alex
  • 1,630
  • 1
  • 20
  • 31
  • possible duplicate of [Remove extra space at the end of string using preg\_replace](http://stackoverflow.com/questions/4787219/remove-extra-space-at-the-end-of-string-using-preg-replace) – Michael Irigoyen Mar 10 '15 at 12:26
  • This is a slightly different question than http://stackoverflow.com/questions/4787219/remove-extra-space-at-the-end-of-string-using-preg-replace which asks how to remove only the space at end of string where my question is for both start and end. The solution for this is different than the question raised by @daron – Alex Mar 10 '15 at 15:32

2 Answers2

74

If it's only white-space, why not just use trim()?

animuson
  • 53,861
  • 28
  • 137
  • 147
6

Yep, you should use trim() I guess.. But if you really want that regex, here it is:

((?=^)(\s*))|((\s*)(?>$))
Gaute Løken
  • 7,522
  • 3
  • 20
  • 38
  • 1
    thanks this solution works as well: preg_replace( '/^((?=^)(\s*))|((\s*)(?>$))/si', '', " asd asd " ); – Alex Nov 05 '11 at 19:53