vvatashi/bbcode

此包已被 废弃 且不再维护。未建议替代包。

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 解析器

一个简单的库,用于解析 BBCodes 并从它生成 HTML 标记。(但不仅限于 HTML。)

安装

composer require vvatashi/bbcode:^2.0

要求

  • Composer;
  • PHP 7.0+(7.1+ 以运行测试)。

使用

$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>

标签定义

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

参数

  • attributePattern (string, 默认 '') - 用于验证标签属性的正规表达式。使用空字符串以禁止此标签上的属性。
  • outputFormat (string, 默认 '<{name}>{content}</{name}>') - 用于生成输出的格式字符串。它可以包含以下占位符
    • {name} - 标签的名称。
    • {attribute} - 标签的属性。
    • {content} - 标签的内容。
  • rawContent (boolean, 默认 false) - true 以在此标签内不解析 BBCodes。用于如 [code] 之类的 BBCodes。

边缘情况

  • 未知标签和具有无效属性的标签将被视为纯文本;
  • 没有关闭标签的开启标签将被关闭;
  • 没有开启标签的关闭标签将被视为纯文本;
  • 无效嵌套的标签将被重新排序以生成有效的树,因此 [a][b][/a][/b] 变为 [a][b][/b][/a][b][/b]