1

I trying to get the values from a string by a regular expression pattern, it works, but it will return all matched strings (I mean the string with {} too)

this is the string:

dashboard/admin/{content}/category/{category}/posts

Regex pattern:

/{(.*?)}/

and the PHP code is :

    preg_match_all('/{(.*?)}/', $url, $matches, PREG_SET_ORDER, 0);

and the content of $matches is:

array:2 [
  0 => array:2 [
    0 => "{content}"
    1 => "content"
  ]
  1 => array:2 [
    0 => "{category}"
    1 => "category"
  ]
]

but I want to have an array like this:

array:2 [
  0 => "content",
  1 => "category"
]
Emma
  • 27,428
  • 11
  • 44
  • 69
MajAfy
  • 3,007
  • 10
  • 47
  • 83
  • 1
    So what have you tried? Just iterate over the matches and select `$match[1]` will do the trick to transform your actual result to the desired one. – Kryptur May 20 '19 at 11:22

3 Answers3

1

Remove the PREG_SET_ORDER so that the index's are by capture group.

preg_match_all('/{(.*?)}/', 'dashboard/admin/{content}/category/{category}/posts', $matches);

with this use $matches[1], because 1 will be the first capture group. The 0 index will be all full matches.

user3783243
  • 5,368
  • 5
  • 22
  • 41
1

Use lookaround:

$url = 'dashboard/admin/{content}/category/{category}/posts';
preg_match_all('/(?<={).*?(?=})/', $url, $matches, PREG_SET_ORDER, 0);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => content
        )

    [1] => Array
        (
            [0] => category
        )

)
Toto
  • 89,455
  • 62
  • 89
  • 125
0

You could make use of \K and a single positive lookahead to assert what is on the right is a }:

{\K[^}]+(?=})

Regex demo

$url = 'dashboard/admin/{content}/category/{category}/posts';
preg_match_all('/{\K[^}]+(?=})/', $url, $matches);
print_r($matches[0]);

Result:

Array
(
    [0] => content
    [1] => category
)

Php demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70