Change your regex to:
"#(admin/pages(?:/\d+)?|admin/pages/add)#"
You don't need both variants (admin/pages|admin/pages/[0+9]+
) if you put the digits in the first pattern and make them optional.
Question marks and repetitions are greedy by default, that's why it will always include the digits in the match for my version.
On the other hand, if you have an alternation, it will always pick the first match. Since your first alternation does not include digits, they are not matched.
If you're also wondering why you get your match two times, that's because of the way preg_match
works.
Quote from the documentation:
$matches[0] will contain the text that matched the full pattern,
$matches[1] will have the text that matched the first captured
parenthesized subpattern, and so on.
You can remove the outer parentheses if the whole match is enough:
"#admin/pages(?:/\d+)?|admin/pages/add#"
Just use $matches[0]
.
And, as @RomanPerekhrest has written and I shamelessly include in this answer, you can shorten your pattern. You don't need to include admin/pages
multiple times:
"#admin/pages(?:/add|/\d+)?#"