ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.


BBCode Format Function

This function can be used in your scripts to use BBCode.

function bbcode_format ($str) {
$str htmlentities($str);

$simple_search = array(

$simple_replace = array(

// Do simple BBCode's
$str preg_replace ($simple_search$simple_replace$str);

// Do 
    $str bbcode_quote ($str);


bbcode_quote ($str) {
$open '
$close '

// How often is the open tag?
preg_match_all ('/\[quote\]/i'$str$matches);
$opentags count($matches['0']);

// How often is the close tag?
preg_match_all ('/\[\/quote\]/i'$str$matches);
$closetags count($matches['0']);

// Check how many tags have been unclosed
    // And add the unclosing tag at the end of the message
$unclosed $opentags $closetags;
    for (
$i 0$i $unclosed$i++) {
$str .= '

// Do replacement
$str str_replace ('[' 'quote]'$open$str);
$str str_replace ('[/' 'quote]'$close$str);


5 Responses to “BBCode Format Function”

  1. Peter Jay Salzman Says:

    Very nice article. But shouldn’t this:

    $str = str_replace (’

    ‘, $open, $str);
    $str = str_replace (’

    ‘, $close, $str);

    be this:

    $str = str_replace (’[ quote]’, $open, $str);
    $str = str_replace (’[ /quote’, $close, $str);

    Note the superfluous space to prevent the bbcode from being interpreted as bbcode!

  2. Dennis Pallett Says:

    You’re right, and I’ve fixed the code above. Thanks for letting me know!

  3. PHPit - Totally PHP » PHP Security: Basic PHP Security Says:

    […] Codesnippets […]

  4. KinG Says:

    hoho, looks like mine, doesn’t it ;)

    but the second part is pretty neat to me, the idea of checking unclosed tags can be extended easily to all tags i suppose :)

  5. Midnight Says:

    Hey I have a site and it posts info into the database but it can’t post html so I want to add bb codes to it and on the page that it shows the data it doesn’t replace [b]text[/b] into a bolded text. Can someone help me out.

Leave a Reply