phpregexpreg-matchtext-extractiondelimited

Regex pattern with optional segments failing to match slash-delimited string


When using preg_match, why #^(([a-z]{2})/)?(([a-z\-]{3,})/(([a-z\-]{3,}))?)?$#i match ab/cde/fgh and do not match ab/cde?

I mean:

preg_match_all('#^(([a-z]{2})/)?(([a-z\-]{3,})/(([a-z\-]{3,}))?)?$#i','ab/cde/fgh',$match)

$match =  Array
(
    [0] => ab/cde/fgd
    [1] => ab/
    [2] => ab
    [3] => cde/fgd
    [4] => cde
    [5] => fgd
    [6] => fgd
)

and

preg_match_all('#^(([a-z]{2})/)?(([a-z\-]{3,})/(([a-z\-]{3,}))?)?$#i','ab/cde',$match)
$match = Array ()

Solution

  • Because as the regex is written, you need a slash after the cde. ab/cde/ should match.