短代码/ BBcode正则表达式

问题描述 投票:0回答:1

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

我在我的系统中使用短代码并且它们工作得非常好。我已经对其属性等进行了排序,但现在我想在其他短代码中使用短代码。

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

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

任何想法如何分类?

非常感谢Tomasz

php regex shortcode regular-language bbcode
1个回答
2
投票

如果数据仅使用标记分隔符[]而不是<>来制作XML标准,则可以将数据转换为XML并使用XML解析器进行进一步分析:

$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);
        //...
    }
}

像这样你不必再发明轮子。

© www.soinside.com 2019 - 2024. All rights reserved.