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.
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.
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.)
strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.
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.
If it's only white-space, why not just use trim()
?
Yep, you should use trim() I guess.. But if you really want that regex, here it is:
((?=^)(\s*))|((\s*)(?>$))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With