删除字符串开头和结尾的空格
我对正则表达式还很陌生。 我需要清理搜索字符串开头和结尾的空格。 示例:“搜索字符串” 结果:“搜索字符串”
我有一个可以作为 javascript 解决方案使用的模式,但我无法使用 preg_replace 在 PHP 上使用它:
有效的 Javascript 模式:
/^[\s]*(.*?)[\s]*$/ig
我的示例:
$string = preg_replace( '/^[\s]*(.*?)[\s]*$/si', '', " search string " );
print $string; //returns nothing
在解析时,它告诉我 g 无法识别,所以我不得不删除它并将 ig 更改为 si。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果只是空白,为什么不直接使用
trim()
呢?If it's only white-space, why not just use
trim()
?是的,我想你应该使用trim()..但如果你真的想要那个正则表达式,这里是:
Yep, you should use trim() I guess.. But if you really want that regex, here it is: