Capturing part of the string between certain characters repeated N times

3

I have a string that has the format of routes:

/foo/
/{bar}/
/foo/{bar}
/{foo}/{bar}
/{foo}/bar/

Can have many values between slashes, values between {} are variable

I wanted to catch all occurrences of {qualquercoisa} of these strings, for example:

/foo/{bar}     =>   ["bar"]
/foo/bar       =>   []
/{foo}/{bar}/  =>   ["foo", "bar"]

I tried with preg_match , but could only capture one occurrence:

preg_match("/\{([^\/]+)\}/", "/foo/{bar}/{baz}/", $match);
//$match = ["{bar}", "bar"]
preg_match("/(?:\{([^\/]+)\}\/?|[^\/]+\/?)+/", "/foo/{bar}/{baz}/", $match);
//$match = ["foo/{bar}/{baz}/", "baz"]

How to capture all occurrences?

    
asked by anonymous 13.09.2018 / 15:52

1 answer

3

To capture more than one occurrence, you need to use the preg_match_all() function. Married values are entered in the third.

Use a simpler regex, case the value of the keys in a group

$str = '/{foo}/{bar}';

 preg_match_all('#{([\w]+)}#', $str, $m);

 echo "<pre>";
 print_r($m);

Output:

Array

(
    [0] => Array
        (
            [0] => {foo}
            [1] => {bar}
        )

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

)
    
13.09.2018 / 16:32