waiwai933
waiwai933

Reputation: 14559

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

Upvotes: 0

Views: 339

Answers (5)

Alana Storm
Alana Storm

Reputation: 166066

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!

Upvotes: 1

Daren Schwenke
Daren Schwenke

Reputation: 5478

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.

Upvotes: 1

Ollie Saunders
Ollie Saunders

Reputation: 8057

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

Upvotes: -1

joebert
joebert

Reputation: 2663

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

Upvotes: 3

RageZ
RageZ

Reputation: 27313

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

Upvotes: 0

Related Questions