jBBCode - a fast, flexible BBCode parser

Examples

  1. Loading and using the default bbcodes
  2. Closing unclosed tags
  3. Getting text without markup
  4. Defining new bbcodes

Loading and using the default bbcodes

jBBCode ships with some basic, optional bbcodes. They're loaded into the parser through the DefaultCodeDefinitionSet class. To get started we just instantiate a parser, load the default bbcodes and parse a simple string of bbcode, printing the result.
<?php
require_once "/path/to/jbbcode/Parser.php";

$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());

$text = "The default codes include: [b]bold[/b], [i]italics[/i], [u]underlining[/u], ";
$text .= "[url=http://jbbcode.com]links[/url], [color=red]color![/color] and more.";

$parser->parse($text);

print $parser->getAsHtml();

Output: The default codes include: bold, italics, underlining, links, color! and more.

Closing unclosed tags

jBBCode is capable of creating well-formed bbcode from poorly-formed code. Once the parse tree is constructed, calling getAsBBCode() will return the parse tree as bbcode. Any unclosed tags will be closed, as demonstrated here:
<?php
require_once "/path/to/jbbcode/Parser.php";

$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());

$text = "The bbcode in here [b]is never closed!";
$parser->parse($text);

print $parser->getAsBBCode();

Output: The bbcode in here [b]is never closed![/b]

Getting text without markup

A lot of websites provide "teasers" of posts, displaying the first paragraph of a post without any formatting. jBBCode makes it easy to do this with the getAsText() method. This method recursively travereses the parse tree, only returning the concatenation of any text nodes.
<?php
require_once "/path/to/jbbcode/Parser.php";

$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());

$text = "[b][u]There is [i]a lot[/i] of [url=http://en.wikipedia.org/wiki/Markup_language]markup[/url] in this";
$text .= "[color=#333333]text[/color]![/u][/b]";
$parser->parse($text);

print $parser->getAsText();

Output: There is a lot of markup in this text!