Capture part of the string between certain repeated characters N times

Asked

Viewed 32 times

3

I have a string that has the format of routes:

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

Can have numerous values between bars, values between {} are variable

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

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

I tried with preg_match, but I was only able to capture one incident:

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?

1 answer

3


To capture more than one occurrence it is necessary to use the function preg_match_all() the married values are inserted 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);

Exit:

Array

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

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

)
  • What a mess to forget the _all, thanks for the help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.