Search code examples
phpregexpreg-replacebbcode

Preg_replace multiple bbcodes correctly


Currenlty I'm creating a bbCodes function to replace all bbCodes by their corresponding HTML codes within a text. My code works like this atm:

public function bbCodes($text) {

    global $bb_codes;

    $text = preg_replace(array_keys($bb_codes), array_values($bb_codes), $text);

    return $text;

}

where $bb_codes looks like this:

$bb_codes = array(
            "/\[b\](.*)\[\/b\]/is" => "<b>$1</b>",
            "/\[u\](.*)\[\/u\]/" => "<u>$1</u>",
            "/\[i\](.*)\[\/u\]/" => "<i>$1</i>",
            "/\[d\](.*)\[\/d\]/" => "<del>$1</del>",
            "/\[url=(.*)\](.*)\[\/url\]/" => "<a href='$1'>$2</a>"
              );

It's working when each bbcode is only used once, e.g.:

[b]this text is bold[/b]
[i]this text is italic[/i]
etc..

But as soon as I use one bbcode tag multiple times it gets messed up:

   [b]this text is bold[/b]
   [i]this text is italic[/i]
   [b]this text is bold too[/b]

It will see the first [b] tag and look for another [/b] tag but it takes the last one instead of the first one it encounters (in the above example all the text will be bold and the first [b] and last [/b] will be replaced only). Does anyone know what I've done wrong and how I can fix this?

Thanks in advanced!

Cheers.


Solution

  • You need to use non greedy wildcard, instead of all the .* write .*?.