Symfony Constraints: Regex for resolution

  php, regex, symfony

I’m trying to validate a parameter structure that should match values like: 1200x800 , 1200x, x800 or simply x
And so i’m using the following constraint:

'size' => [
                new AssertNotBlank(),
                new AssertRegex([
                    'pattern' => '/(d+)?x(d+)?/i'
                ])
            ],

The regex works fine as a standalone, but inside symfony constraint it also match cases like 1200x800x500.
Im guessing behind the scene that it uses the preg_match_all? That would explain it since using: preg_match_all('/(d+)?x(d+)?/i', $data['size'], $size);, gives the following result:

array:3 [▼
  0 => array:2 [▼
    0 => "1500x800"
    1 => "x500"
  ]
  1 => array:2 [▼
    0 => "1500"
    1 => ""
  ]
  2 => array:2 [▼
    0 => "800"
    1 => "500"
  ]
]

Is there a way to make it stop at the first occurrence? Basically allow only: 1200x800 , 1200x, x800 or simply x

Source: Ask PHP

LEAVE A COMMENT