Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
Alex Avatar asked Nov 05 '11 19:11

Alex


People also ask

How do I remove spaces at the start and end of a string in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

Which method removes whitespace from both ends of a string?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)

How do I remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.

How do you remove spaces at the end of a string in Java?

Java has inbuilt methods to remove the whitespaces from the string whether leading, trailing, both, or all. trim() method removes the leading and trailing spaces present in the string. strip method removes the leading and trailing spaces present in the string. Also, it is Uniset/Unicode character aware.


2 Answers

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

like image 186
animuson Avatar answered Sep 24 '22 05:09

animuson


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

((?=^)(\s*))|((\s*)(?>$)) 
like image 25
Gaute Løken Avatar answered Sep 24 '22 05:09

Gaute Løken