开发者

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 ?


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


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜