删除字符串开头和结尾的空格

发布于 2024-12-13 21:18:26 字数 401 浏览 3 评论 0原文

我对正则表达式还很陌生。 我需要清理搜索字符串开头和结尾的空格。 示例:“搜索字符串” 结果:“搜索字符串”

我有一个可以作为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

杀手六號 2024-12-20 21:18:26

如果只是空白,为什么不直接使用 trim() 呢?

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

千鲤 2024-12-20 21:18:26

是的,我想你应该使用trim()..但如果你真的想要那个正则表达式,这里是:

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

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

((?=^)(\s*))|((\s*)(?>$))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文