PHP PCRE 的问题
我在使用 PHP PCRE 时遇到问题,而且我习惯了 POSIX,所以我不太确定我做错了什么。基本上,此函数最多匹配 10 个以逗号分隔的数字。然而,它也匹配字符串 sdf (可能还有许多其他字符串),我不明白原因。谁能帮助我吗?
$pattern='^\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?^';
$leftcheck=preg_match($pattern, $leftmodules);
$centercheck=preg_match($pattern, $centermodules);
$rightcheck=preg_match($pattern, $rightmodules);
if(!$leftcheck OR !$centercheck OR !$rightcheck)
{
$editpage = $_SERVER['HTTP_REFERER'].'?&error=1';
die("Location:$editpage");
}
I'm having a problem with PHP PCRE, and I'm used to POSIX, so I'm not too sure about what I'm doing wrong. Basically, this function is matching up to 10 numbers separated by commas. However, it's also matching the string sdf
(and probably many others), which I don't see the reason for. Can anyone help me?
$pattern='^\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?\d{0,5},? ?^';
$leftcheck=preg_match($pattern, $leftmodules);
$centercheck=preg_match($pattern, $centermodules);
$rightcheck=preg_match($pattern, $rightmodules);
if(!$leftcheck OR !$centercheck OR !$rightcheck)
{
$editpage = $_SERVER['HTTP_REFERER'].'?&error=1';
die("Location:$editpage");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我假设如下:
鉴于此:
有效。
I'm assuming the following:
Given that:
works.
据我所知,您提供的正则表达式将与您传递给它的任何内容匹配。这就是为什么
你的正则表达式本质上是短路的。引擎看到字符串的第一个字符并说“某个数字重复了 0 次吗?是吗?好的,这是一个匹配!”
From what I can see, the regular expression you provided will match anything you pass into it. Here's why
So your regular expression is essentially short circuiting. The engine see the first character of your string and says "has a digit been repeated 0 times? Yes? OK, it's a match!
我认为如果你的号码仅用逗号分隔,类似这样的事情应该可以做到
I think if your number are only separated by commas something like this should do it
您需要将模式包含在两个相等的符号之间才能使其有效。人们通常使用/。
为了匹配整个内容,您希望在开头添加 ^,在结尾添加 $。出现这个错误可能就是您的 sdf 匹配的原因。
如何分隔数字有点令人困惑。是逗号还是空格?两者都可以吗?没有呢?不过,这是我最好的猜测。
You need to contain the pattern between two equal symbols for it to be valid. People usually use /.
To match the whole thing you want to have ^ at the start and $ at the end. Getting this wrong is probably why your
sdf
was matching.It's a bit confusing how the numbers will be separated. Is it comma or space? Is both OK? What about none? Here's my best guess though.