phppreg-replacebbcode

preg replace multiple results


I'm currently writing a function in PHP to translate BBCodes for a forum engine. Now I wanted to add a [code]-tag and I created the following function:

$txt = preg_replace('#\[code\](.*)\[(.*)\[/code\]#isU', "<div class=\"bb_uncode\">$1&#91;$2</div>", $txt); 

(Side note: &#91; equals [)
This works very well if there's only one [ inside the [code]-tags, but it ignores every further one.
Is there a possiblity to apply this search pattern on every other brackets, too?


Solution

  • Do this with preg_replace_callback():

    $txt = preg_replace_callback('#\[code\](.*)\[/code\]#isU', function($match) {
        return "<div class=\"bb_uncode\">" . 
               str_replace('[', '&#91;', $match[1]) .
               "</div>"); 
    }, $txt);