Remove spaces from the beginning and end of a string

Alex picture Alex · Nov 5, 2011 · Viewed 50k times · Source

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.

Answer

animuson picture animuson · Nov 5, 2011

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