我如何使这个 preg_match() reg 表达式忽略空格?

发布于 2024-10-08 23:18:50 字数 434 浏览 7 评论 0原文

我有这个正则表达式:

if(preg_match("/^(\\d+)(,)(\\d+)$/") ) { ... }

它测试用户是否输入了一对用逗号分隔的数字(例如 120,80)。我已经让那部分工作正常了。不过,我预计用户可能会意外地在任何字符之间输入空格。我想让表达式忽略所有空白字符,无论它们出现在模式中的位置。我已经尝试过这个:

if(preg_match("/x^(\\d+)(,)(\\d+)$/x") ) { ... }

还有这个:

if(preg_match("/(^(\\d+)(,)(\\d+))$/x") ) { ... }

但似乎没有任何效果。任何见解将不胜感激。顺便说一句,我仍在学习这些东西,所以请考虑到这一点!谢谢。 :D

I have this regular expression:

if(preg_match("/^(\\d+)(,)(\\d+)$/") ) { ... }

which tests that the user has entered a pair of numbers separated by a comma (e.g. 120,80). I've got that part working properly. However I anticipate that users may accidentally enter white space between any of the characters. I would like to make the expression ignore ALL white space characters, no matter where they occur in the pattern. I've tried this:

if(preg_match("/x^(\\d+)(,)(\\d+)$/x") ) { ... }

And also this:

if(preg_match("/(^(\\d+)(,)(\\d+))$/x") ) { ... }

But nothing seems to work. Any insights would be greatly appreciated. BTW I'm still learning this stuff so take that into account! Thanks. :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

对风讲故事 2024-10-15 23:18:50

您可以在进行正则表达式匹配之前删除空格。

$input = str_replace(" ", "", $input);

You might just strip whitespace before you do your regex match.

$input = str_replace(" ", "", $input);
似梦非梦 2024-10-15 23:18:50

尝试:

if(preg_match("/^\s*\d+\s*,\s*\d+\s*$/",$input) ) { 
   // $input has two numbers separated by a comma and may have whitespace
   // around the number and/or around the comma.
}

Try:

if(preg_match("/^\s*\d+\s*,\s*\d+\s*$/",$input) ) { 
   // $input has two numbers separated by a comma and may have whitespace
   // around the number and/or around the comma.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文