I have the following sample text
The quick brown {fox} jumps over the lazy {dog}
I need to match any string enclosed in {} which can occur several times in the text.
I tried the following code but it doesn’t work properly
<?php
$matches = array();
$string = "The quick brown {fox} jumps over the lazy {dog}";
preg_match("/\{(.*)\}/",$string,$matches);
print_r($matches);
?>
and that’s what I get
Array
(
[0] => {fox} jumps over the lazy {dog}
[1] => fox} jumps over the lazy {dog
)
I would expect getting
Array
(
[0] => {fox} jumps over the lazy {dog}
[1] => fox
[2] => dog
)
So how can I force PHP to match the nearest “}” instead of matching the last one ?
Your existing regex has
.*which is greedy and tries to consume as much as possible. To fix this you need to make the regex non-greedy by adding a?at the end as:alternatively you can also use
[^}]*in place of.*.And since you want all matches, you need to use
preg_match_allSee it