开发者

Preg match all greedy with exception for string

My source string is this:

{categories group_id="3"}
{category_name}
{/categories}

{categories group_id="4"}
{category_name}
{/categor开发者_开发问答ies}

My regex is this:

preg_match('/{categories group_id="3"}(.*){\/categories}/s', $tagdata, $matches);

Which results in:

Array
(
    [0] => Array
        (
            [0] => {categories group_id="3"}
    {category_name}
    {/categories}
    {categories group_id="4"}
    {category_name}
    {/categories}
        )

    [1] => Array
        (
            [0] => 
    {category_name}
    {/categories}
    {categories group_id="4"}
    {category_name}

        )
)

You can see that the greediness is too greedy, and it goes all the way to the end of the second instance. What I'm expecting is this:

Array
(
    [0] => Array
        (
            [0] => {categories group_id="3"}
    {category_name}
    {/categories}
        )

    [1] => Array
        (
            [0] => 
    {category_name}

        )
)


.*  greedy
.*? non-greedy


Agree with @user779

Also another way is to add a U (PCRE_UNGREEDY) modifier at the end of your regexp which makes all quantifiers lazy.

preg_match('/{categories group_id="3"}(.*){\/categories}/sU', $tagdata, $matches);

More info here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜