potaka/bbcode

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

bb代码的php解析器

0.2.1 2017-02-24 19:18 UTC

This package is not auto-updated.

Last update: 2020-10-30 21:07:24 UTC


README

构建

SensioLabsInsight

Build Status

该包分为两部分 - 分词器和解析器。

分词 - 将字符串转换为标记。

BbCodeParser - 将bb代码标记转换为html(+一些验证)

简单方法

$tokenizer = new \Potaka\BbCode\Tokenizer\Tokenizer();

$bbText = '[b]bold[/b]text[u]under[i]line[/i][/u]';

$tokenized = $tokenizer->tokenize($text);
$factory = new  \Potaka\BbCode\Factory();
$bbcode = $factory->getFullBbCode();
$html = $bbcode->format($tokenized);

如果 html 的值为

<b>bold</b>text<u>under<i>line</i></u>

安装

composer require potaka/bbcode

内部说明

分词

例如

$bbText = '[b]bold[/b]text[u]under[i]line[/i][/u]';

将被分词为

Tag:
  type: null,
  tags:
    tag1:
      type: b
      tags:
        tag1:
          type: null
          text: bold
    tag2:
      type: null
      text: text
    tag3:
      type: u
      tags:
        tag1:
          type: null,
          text: under
        tag2:
          type: i
          tags:
            tag1:
              type: null,
              text: line

分词为html

你需要有效的 bb代码标签。内置标签在 https://github.com/angelk/bbCode/tree/master/src/Potaka/BbCode/Tag 中可用

构建解析器

use Potaka\BbCode;
use Potaka\BbCode\Tokenizer;

use Potaka\BbCode\Tag\Bold;
use Potaka\BbCode\Tag\Underline;
use Potaka\BbCode\Tag\Italic;

use Potaka\BbCode\Tag\Link;

$bbcode = new BbCode();

让我们添加 b 代码

$bold = new Bold();
$bbcode->addTag($bold);

让我们格式化上面的标记

$tokenizer = new Tokenizer();
$tokenized = $tokenizer->tokenize($bbText);

$bbcode->format($tokenized);

将返回

<b>bold</b>text[u]under[i]line[/i][/u]

ui 没有格式化,因为没有添加标签。

让我们添加它们。

$underline = new Underline();
$bbcode->addTag($underline);

$italic = new Italic();
$bbcode->addTag($italic);

再次测试

$bbcode->format($tokenized);

结果

<b>bold</b>text<u>under[i]line[/i]</u>

为什么 i 没有被转换?因为 u 不允许 i 类型的子标签。让我们修复这个问题

$bbcode->addAllowedChildTag($underline, $italic);

现在一切应该都正常工作了!

这种允许的目的何在?想象一下你有链接 [url]http://google.bg[/url]。如果有人尝试在 [url=http://google.bg]google.[url=http://gmail.com]bg[/url][/url] 中放入链接,会发生什么?这将生成

<a href="http://google.bg">
  google.<a href="http://gmail.com">bg</a>
</a>

这个html是无效的。它甚至可能提供 xss。这就是为什么你不应该在 url 内部允许 url 的原因。