PHP PCRE的问题

问题描述:

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");
}

我遇到了PHP PCRE的问题,而且我习惯了POSIX,所以我也不是 确定我做错了什么。 基本上,此函数最多匹配10个以逗号分隔的数字。 但是,它也匹配字符串 sdf code>(可能还有许多其他字符串),我没有看到原因。 任何人都可以帮助我吗? p>

  $ 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”)  ; 
} 
  code>  pre> 
  div>

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

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

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!