Skip to content
PHP Logo

How can text be formatted using bb codes in PHP?

To format text using bb codes in PHP, you can use regular expressions to match the bb codes and replace them with the corresponding HTML tags. This allows you to easily convert bb code formatted text into properly formatted HTML.

php
function formatBBCode($text) {
    $bbCodes = array(
        '/\[b\](.*?)\[\/b\]/s' => '<strong>$1</strong>',
        '/\[i\](.*?)\[\/i\]/s' => '<em>$1</em>',
        '/\[u\](.*?)\[\/u\]/s' => '<u>$1</u>'
    );

    foreach ($bbCodes as $bbCode => $htmlTag) {
        $text = preg_replace($bbCode, $htmlTag, $text);
    }

    return $text;
}

$text = "[b]Bold[/b] [i]Italic[/i] [u]Underline[/u]";
echo formatBBCode($text);