开发者

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 soo开发者_C百科n 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.


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


Why you're not using BBCode Parser ? Look at NBBC Parser.

To install it just put it into usefull folder on your server and connect it like it written in link I've provided later : )

<?php
    require_once("nbbc.php");
    $bbcode = new BBCode;
    print $bbcode->Parse("[i]Hello, World![/i]  This is the magic of [b]BBCode[/b]!");
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜