yceruto
yceruto

Reputation: 9585

regular expression matching order issue

I have the following code:

preg_match(
    '/(,\s?min\s?(?P<min>[\d]+)\s?)?(,\s?max\s?(?P<max>[\d]+)\s?)?/', 
    ',max 1, min 2', 
    $vars
);

So, the matching result is:

//var_dump($vars):

array (size=7)
  0 => string ',max 1' (length=6)
  1 => string '' (length=0)
  'min' => string '' (length=0)
  2 => string '' (length=0)
  3 => string ',max 1' (length=6)
  'max' => string '1' (length=1)
  4 => string '1' (length=1)

As can appreciate the value of min it is empty ''.

I need help to get the value of the data min and max regardless of the order they appear in the string.

Thanks.

Upvotes: 1

Views: 44

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You can use the following regex:

(?J)(?:,\s?min\s?(?P<min>\d+)\s?)(?:,\s?max\s?(?P<max>\d+)\s?)?|(?:,\s?max\s?(?P<max>\d+)\s?)(?:,\s?min\s?(?P<min>\d+)\s?)?

See regex demo

The regex is basically yours, I just added a (?J) modifier that allows reusing capture names in the same regex, and added an alternative with another order of min and max. Also, I removed square brackets from around \d.

Ideone demo:

$re = '/(?J)(?:,\s?min\s?(?P<min>\d+)\s?)(?:,\s?max\s?(?P<max>\d+)\s?)?|(?:,\s?max\s?(?P<max>\d+)\s?)(?:,\s?min\s?(?P<min>\d+)\s?)?/'; 
if (preg_match($re, ",max 1, min 2", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ",min 5, max 6", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ", min 7", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"] . PHP_EOL);
}
if (preg_match($re, ",max 8", $matches)){
    print_r($matches["max"] . " = max and min = " . $matches["min"]);
}

Results:

1 = max and min = 2
6 = max and min = 5
 = max and min = 7
8 = max and min = 

Upvotes: 1

anubhava
anubhava

Reputation: 785611

To grab min and max irrespective of their order you can use this alternation based regex:

\b(?:min\h+\K(?<min>\d+)|max\h+\K(?<max>\d+))\b

RegEx Demo

Use captured group names min and max to extract the value from resulting array after preg_match_all function call.

Upvotes: 1

Related Questions