Shortcodes/BBcode 正则表达式

Shortcodes/BBcode regular expression

我在编写正确的正则表达式时遇到问题。

我在我的系统中使用简码,它们运行得非常好。我已经对它的属性等进行了排序,但现在我想在另一个短代码中使用一个短代码。

这是我准备正则表达式的方式:

$attributes_regexp = "([^\]]*?)";
$inner_content_regexp = "(.*?)";
$flags_regexp = "im";
$regexp = "/\[$shortcode$attributes_regexp\]$inner_content_regexp\[\/$shortcode\]/$flags_regexp";
preg_match_all($regexp, $content, $found_occurrences);

下面是一个现成的正则表达式示例:

\[file([^\]]*?)\](.*?)\[\/file\]

这里有一些必须分析的HTML:

<div class="row">
<div class="col-md-8">
<h2>Test page</h2>
<p>&nbsp;</p>
<p><strong>Some</strong> content</p>
<p>Lorem ipsum dolor.&nbsp;</p>
<p>Dolor sit amet.</p>
<p>[file id=290 type=link][file id=283 type=image width=100 height=100][/file][/file]</p>
</div>
<div class="col-md-3 offset-md-1">
<p>[file id=289 type=image][/file]</p>
</div>
</div>

问题是只有最后一个将其更改为图像才能正确获取,但上一个像

[file id=290 type=link][file id=283 type=image width=100 height=100][/file]

而不是两个单独的

[file id=283 type=image width=100 height=100][/file]

[file id=290 type=link][/file]

知道如何排序吗?

非常感谢, 托马斯

如果数据仅使用标签分隔符 [] 而不是 <> 来打破 XML 标准,您可以转换数据进入 XML 并使用 XML-parser 进行进一步分析:

$regex = "/(\[{$shortcode}.+\[\/{$shortcode}\])/";
if (preg_match_all($regex, $content, $matches)) {
    array_shift($matches); //removes $matches[0], which contains the whole $content again
    foreach ($matches as $match) {
        //The following line should turn your data into valid XML
        $xml = str_replace(['[', ']'], ['<', '>'], $match);
        //Some XML parsing like:
        $xmlObject = new SimpleXMLElement($xml);
        //...
    }
}

这样就不用再造轮子了