Please fix this Regex for nested tags

Discussion in 'PHP' started by rjpzf, Sep 4, 2009.

  1. #1
    I'm trying to nest tags with regex.

    It's a "for" loop. This is the code I have so far:

    <?php 
    $test = "{for:a in b}
    For1
    {for:c in d}
    For2
    {/for}
    {for:e in f}
    Nothing
    {/for}
    {/for}";
    
    $pattern = '#\{for:(.*)\sin\s(.*)}((?:[^{]|\{(?!/?for})|(?R))+)\{/for}#ms';
    preg_match_all($pattern, $test, $matches);
    print_r($matches);
     ?>
    PHP:
    The problem is that when I add any attributes to the "for" tag, the regex stops working. So I have {for:a in b} right now, but, if I remove everything so it reads just {for}, it will work. For example, this works:

    This code is WORKING:

    <?php 
    $test = "{for}
    For1
    {for}
    For2
    {/for}
    {for}
    Nothing
    {/for}
    {/for}";
    
    $pattern = '#\{for}((?:[^{]|\{(?!/?for})|(?R))+)\{/for}#';
    
    preg_match_all($pattern, $test, $matches);
    print_r($matches);
     ?>
    PHP:
    Can anyone help? It would be best if you can provide an explanation to why your fix works and mine doesn't, but it's not necessary, I just need the code/fix.

    Thanks.
     
    rjpzf, Sep 4, 2009 IP
  2. sarikabtech

    sarikabtech Well-Known Member

    Messages:
    186
    Likes Received:
    3
    Best Answers:
    1
    Trophy Points:
    108
    #2
    refrain greedy search.
    use (.*?)
    in
    '#\{for:(.*)\sin\s(.*)}...........
     
    sarikabtech, Sep 6, 2009 IP