开发者

Problems with PHP PCRE

开发者 https://www.devze.com 2022-12-08 05:49 出处:网络
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

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 = $_SERV开发者_如何转开发ER['HTTP_REFERER'].'?&error=1';
die("Location:$editpage");
}


^\d{1,5}(, *\d{1,5}){0,9}$


I'm assuming the following:

  • Spaces may or may not be there.
  • Numbers can be any length.
  • Only numbers, spaces, and comma's are allowed.
  • Trailing commas without a number after them are allowed.
  • Between 1 and 10 numbers seperated by commas are ok.

Given that:

$pattern = '/^(\d+,* *){1,10}$/';

works.


From what I can see, the regular expression you provided will match anything you pass into it. Here's why

\d{0,5}     #\d matches any digit character, while {0,5} means the
            #preceding character must be repeated between **0** and five times

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

$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}$';


You need to contain the pattern between two equal symbols for it to be valid. People usually use /.

$pattern = '/some pattern/';

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.

$pattern = '/^whole pattern match$/';

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.

$pattern = '/^\d{,5}[, ](\d{,5}[, ]){,9}$/';
0

精彩评论

暂无评论...
验证码 换一张
取 消