AssemblerGuy
AssemblerGuy

Reputation: 623

Problem with regular expression matching order in PHP

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 ?

Upvotes: 1

Views: 157

Answers (3)

codaddict
codaddict

Reputation: 455302

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_all

See it

Upvotes: 3

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146540

By default, expressions are greedy, i.e., they try to grab the longest possible matches. You can make an expression ungreedy with the U flag:

preg_match('/\{(.*)\}/U', $string, $matches);

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212452

By default, your regexp is executed in greedy mode. You need ungreedy. Either use the /U switch, or codaddict's suggestion of *.? to make that part of the expression ungreedy

Upvotes: 0

Related Questions