The code below will only use the first line in the array (which makes the text bold).

function bbcode($string) {

    $codes = Array(
        '/\[b\](.+?)\[\/b\]/' => '<b>\1</b>',
        '/\[i\](.+?)\[\/i\]/' => '<i>\1</i>',
        '/\[u\](.+?)\[\/u\]/' => '<u>\1</u>',
        '/\[s\](.+?)\[\/s\]/' => '<s>\1</s>',
        '/\[url=(.+?)\](.+?)\[\/url\]/' => '<a href="\1">\2</a>',
        '/\[image=(.+?)\]/' => '<div class="centered"><img src="\1" alt=""></div>'
    );

    while($replace = current($codes)) {
        $bbcode = preg_replace(key($codes), $replace, $string);
        next($codes);

        return stripslashes(nl2br($bbcode));
    }

}

echo bbcode('[b]This text[/b] will be bold and also [b]this text[/b]. But when I use some other BBCodes, it will [u]not[/u] work as planned. Here's a [url=http://google.com/]link[/url] too which will not be replaced as planned.');

Output: This text will be bold and also this text. But when I use some other bbcode, it will [u]not[/u] work as planned. Here's a [url=http://google.com/]link[/url] too which will not be replaced as planned.

How can I do so that my code will search for the right BBCode in the array and replace it with the key?

有帮助吗?

解决方案

preg_replace accepts arrays as well for patterns and replacements.
Use the notation $n in the replacement part instead of \n that is reserved for the pattern.

Here is what I'd do:

function bbcode($string) {
    $codes = Array(
        '/\[b\](.+?)\[\/b\]/' => '<b>$1</b>',
        '/\[i\](.+?)\[\/i\]/' => '<i>$1</i>',
        '/\[u\](.+?)\[\/u\]/' => '<u>$1</u>',
        '/\[s\](.+?)\[\/s\]/' => '<s>$1</s>',
        '/\[url=(.+?)\](.+?)\[\/url\]/' => '<a href="$1">$2</a>',
        '/\[image=(.+?)\]/' => '<div class="centered"><img src="$1" alt=""></div>'
    );
    $bbcode = preg_replace(array_keys($codes), array_values($codes), $string);
    return stripslashes(nl2br($bbcode));
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top