vvatashi/bbcode

This package is abandoned and no longer maintained. No replacement package was suggested.

2.1.1 2019-01-16 19:44 UTC

This package is auto-updated.

Last update: 2020-12-05 14:21:04 UTC


README

Build Status codecov

BBCode parser

A simple library to parse BBCodes and generate HTML markup from it. (But not limited only to HTML.)

Installation

composer require vvatashi/bbcode:^2.0

Requirements

  • Composer;
  • PHP 7.0+ (7.1+ to run tests).

Usage

$tagDefs = [];

// Simple tag definition.
// Output will be rendered as '<tag name>tag content</tag name>' by default.
$tagDefs[] = new TagDef('b');

// Tag with a custom output format string.
$tagDefs[] = new TagDef('i', [
  'outputFormat' => '<em>{content}</em>',
]);

// Tag with an attribute.
$tagDefs[] = new TagDef('color', [
  'attributePattern' => '/#[0-9a-f]{3}/',
  'outputFormat' => '<span style="color: {attribute};">{content}</span>',
]);

// Parse some input and generate HTML:
$parser = new Parser($tagDefs);
$result = $parser->parse('Lorem [b]ipsum [i]dolor[/i][/b] sit amet, [color=#333]consectetur adipiscing elit[color]');
echo $result;

// Should output:
// Lorem <b>ipsum <em>dolor</em></b> sit amet, <span style="color: #333;">consectetur adipiscing elit</span>

Tag definition

new TagDef(string $tagName[, array $additionalParameters])

Parameters:

  • attributePattern (string, default '') - Regular expression used to validate a tag attribute. Use empty string to disallow attribute on this tag.
  • outputFormat (string, default '<{name}>{content}</{name}>') - Format string used to generate output. It can contain following placeholders:
    • {name} - Name of the tag.
    • {attribute} - Attribute of the tag.
    • {content} - Content of the tag.
  • rawContent (boolean, default false) - true to not parse BBCodes inside this tag. Used to BBCodes such as [code].

Edge cases

  • Unknown tags and tags with invalid attributes will be treated as raw text;
  • Opening tag without a closing tag will be closed;
  • Closing tag without an opening tag will be treated as raw text;
  • Tags with invalid nesting will be reordered to generate a valid tree, so [a][b][/a][/b] becomes [a][b][/b][/a][b][/b].