Regular Expressions If Else

I have a line: / foo / {bar} / {baz?}

Now I want to extract all the words inside {...}. But by the word with "?" I want to select not only {...} but also "/" 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 it should be:

Array
(
    [0] => Array
        (
            [0] => {bar}
            [1] => /{baz?}
        )

    [1] => Array
        (
            [0] => bar
            [1] => baz
        )

)

      

(Note the / before the {baz?} Match)

Hope this is clear enough, my english is not that good. Thanks to

+3


source to share


1 answer


Use the reset group ( (?|...|...)

) branch with two capture groups inside that will share the same ID:

/(?|\/{(\w+)\?}|{(\w+)})/

      

See regex demo

More details



  • (?|

    - branch reset group launch
  • \/{(\w+)\?}

    - a /{

    , then 1 + word-symbols (written in group 1) and then?}

  • |

    - or
  • {(\w+)})

    - a {

    followed by 1+ word characters (overwritten in group 1 again) and then }

    .

PHP demo :

$re = '/(?|\/{(\w+)\?}|{(\w+)})/';
$str = '/foo/{bar}/{baz?}';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
print_r($matches);

      

+6


source







All Articles