【问题标题】:Shortcodes/BBcode regular expression简码/BBcode 正则表达式
【发布时间】:2018-06-02 04:04:42
【问题描述】:

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

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

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

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

而不是两个独立的

[文件 id=283 类型=图像宽度=100 高度=100][/file]

和

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

任何想法如何排序?

非常感谢, 托马斯

【问题讨论】:

  • 所以您正在使用正则表达式将 [file id=289 type=image][/file] 之类的内容替换为具有适当属性的 img 标签?
  • 是的,而且效果很好。但现在我需要在另一个里面替换一个。问题是它们都是一样的。

标签: php regex shortcode regular-language bbcode


【解决方案1】:

如果数据仅使用标记分隔符 [ 和 ] 而不是 &lt; 和 &gt; 打破 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);
        //...
    }
}

这样你就不必再发明轮子了。

【讨论】:

  • 谢谢,根据您的解决方案,我重新设计了我的代码,因为不想从头开始编写整个代码。现在,由于您的正则表达式,我首先寻找标签,然后我用我的正则表达式处理它们并将数组反转为从右到左工作并且它完全工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-06-22
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 2011-03-17
  • 1970-01-01
相关资源
最近更新 更多