Alex
Alex

Reputation: 1668

Remove spaces from the beginning and end of a string

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.

Upvotes: 27

Views: 63646

Answers (2)

Gaute Løken
Gaute Løken

Reputation: 7892

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

((?=^)(\s*))|((\s*)(?>$))

Upvotes: 6

animuson
animuson

Reputation: 54719

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

Upvotes: 76

Related Questions