views:

90

answers:

5

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

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}$';
RageZ
+3  A: 
^\d{1,5}(, *\d{1,5}){0,9}$
joebert
You should probably include the the `/.../` delimiters in your pattern.
too much php
A: 

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}$/';
Ollie Saunders
The ^ is being used as the two equal symbols.
Alan Storm
Wow, that's really misleading.
Ollie Saunders
+1  A: 

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.

Daren Schwenke
+1  A: 

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!

Alan Storm