I have a string: /foo/{bar}/{baz?}
Now i want to extract all words inside the {...}. But on the word with the "?" i want to select not only the {...} but also the "/" before "{"
So far i got this:
$string = '/foo/{bar}/{baz?}';
preg_match_all('~{(\w+)[?]?}~', $string, $matches);
print_r($matches);
Result:
Array
(
[0] => Array
(
[0] => {bar}
[1] => {baz?}
)
[1] => Array
(
[0] => bar
[1] => baz
)
)
But should be:
Array
(
[0] => Array
(
[0] => {bar}
[1] => /{baz?}
)
[1] => Array
(
[0] => bar
[1] => baz
)
)
(Notice the / before the {baz?} match)
Hope this is clear enough my english is not so good. Thanks
Use a branch reset group ((?|...|...)) with 2 capturing groups inside that will share the same ID:
/(?|\/{(\w+)\?}|{(\w+)})/
See the regex demo
Details:
(?| - branch reset group start\/{(\w+)\?} - a /{, then 1+ word chars (captured into Group 1) and then ?}| - or{(\w+)}) - a { followed with 1+ word chars (captured into Group 1 again) and then }.$re = '/(?|\/{(\w+)\?}|{(\w+)})/';
$str = '/foo/{bar}/{baz?}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
print_r($matches);