使用php regex在嵌套的foreach循环中选择最里面的foreach

时间:2015-12-01 20:30:09

标签: php regex

我想用php regex在嵌套的foreach循环中选择最里面的foreach循环。

{foreach as $key => $value}
    <div>Content</div>

    {foreach as $anotherKey => $anotherValue}
        <div>Test content</div>
        <p>Test Another Content</p>

        {foreach as $k => $v}
            <p> I want to this area </p>
        {/foreach}
    {/foreach}
{/foreach}

我在单个foreach区域使用以下正则表达式,这是有效的。但对于嵌套的foreach来说,这还不够。

/{foreach (\$\w+) as (\$\w+) => (\$\w+)}(.*?){\/foreach}/ms

1 个答案:

答案 0 :(得分:0)

您可以将.*?替换为[^{]*+(?:{(?!\/?foreach)[^{]*)*+,以防止在其他foreach代码之间匹配“foreach代码”。

结果:

/{foreach (\$\w+) as (\$\w+) => (\$\w+)}([^{]*+(?:{(?!\/?foreach)[^{]*)*+){\/foreach}/

您不需要m或s修饰符。

demo

细节:

[^{]*+              # all that is not a {
(?:                 # open a non capturing group
    {(?!\/?foreach) # a { not followed by "foreach" or "/foreach"
    [^{]*                
)*+                 # repeat the group