preg_match problem?

Discussion in 'PHP' started by yisoras, Feb 9, 2008.

  1. #1
    Hi, I'm trying to make a bbcode feature on my script but I need some help on using of preg_match.

    This code works well.

    $text="[color=blue]text1[/color] [color=green]text2[/color] [color=red]text3[/color]";
     
    preg_match_all('|\[color=(.*?)\](.*?)\[/color\]|si', $text, $match);
    for($i=0;$i<sizeof($match[1]); $i++)
    echo $match[1][$i].'<br>';  
    
    PHP:
    but when I add a bbcode within a bbcode it just doesn't work. Like that;

    $text="[color=blue]text1[/color] [color=green]text2[/color] [color=red]text3  [color=black]text4  [color=brown]text5[/color] [/color] [/color] outside text";
     
    preg_match_all('|\[color=(.*?)\](.*?)\[/color\]|si', $text, $match);
    for($i=0;$i<sizeof($match[1]); $i++)
    echo $match[1][$i].'<br>';  
    
    PHP:
    Could someone help me please?
     
    yisoras, Feb 9, 2008 IP
  2. Cybernaut

    Cybernaut Peon

    Messages:
    408
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Can't be done using regexp. You need to use some parser that can parse nested tags.

    You could just replace every occurence of [ color=xxx ] to <span style="color:xxx;"> and [ /color ] to </span> using regexp if you just need to convert bbcode to html without creating a dom like tree. This will solve the problem of nested tags. Same can be done to other bbcodes.
     
    Cybernaut, Feb 9, 2008 IP
  3. LittleJonSupportSite

    LittleJonSupportSite Peon

    Messages:
    386
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Cyber is correct.

    For the sake of an example basically your trying to do this:


    
    $bold_open="<b>";
    $bold_close="</b";
    $return = eregi_replace("[b]", $bold_open, $return);
    $return = eregi_replace("[/b]", $bold_close, $return);
    
    Code (markup):
    You can make the above code break apart based on color tage open and closed without to much difficulty.

    There are much cleaner ways of doing this via a parser that can actually read through the entire contents.
    But I am giving you the quick and dirty fix =)
     
    LittleJonSupportSite, Feb 9, 2008 IP
  4. jayshah

    jayshah Peon

    Messages:
    1,126
    Likes Received:
    68
    Best Answers:
    1
    Trophy Points:
    0
    #4
    If you want to use preg_match(_all), you could write a recursive function to match the tags, then loop through each one, and match any further tags. May take some work though.

    Jay
     
    jayshah, Feb 10, 2008 IP