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?
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.
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 =)
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