php 删除字符串开头和结尾的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8022759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove spaces from the beginning and end of a string
提问by Alex
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 解决方案的模式,但我无法使用 preg_replace 让它在 PHP 上工作:
Javascript patern that works:
有效的 Javascript 模式:
/^[\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.
在解析时,它告诉我无法识别 g,因此我不得不将其删除并将 ig 更改为 si。
回答by Gaute L?ken
Yep, you should use trim() I guess.. But if you really want that regex, here it is:
是的,你应该使用 trim() 我猜..但如果你真的想要那个正则表达式,这里是:
((?=^)(\s*))|((\s*)(?>$))