我在编写正确的正则表达式上有一个问题。
我正在使用系统中的短代码,它们的工作效果很好。我已经排序了它的属性等,但是现在我想在其他快捷代码内使用短代码。
这是我准备正则表达式的方式:
$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> </p>
<p><strong>Some</strong> content</p>
<p>Lorem ipsum dolor. </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>
问题在于它仅正确地将其更改为映像,但前一个将其视为
[文件ID = 290 type = link] [文件ID = 283 type = 283 type =图像width = 100 height = 100] [/file]
而不是两个独立的
[文件ID = 283 type =图像width = 100 height = 100] [/file]
和
[文件ID = 290 type = link] [/file]
有什么想法可以分类?
非常感谢,tomasz
如果数据仅制动带有标签分离器[
和]
而不是<
和>
的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);
//...
}
}
像这样,您不必再次发明轮子。