正则表达式可以替换一些找到的内容吗?

时间:2017-11-23 06:09:38

标签: php regex

我正在为CMS(Joomla)编写一个插件,以从Joomla文章中提取部件编号,并在其中构建一个包含精确部件号的静态HTML字符串。

整篇文章存储在$ article-> text。

以下是步骤:

  1. 查找{myplugin} ABCDEF1234,“Flux Capacitor”{/ myplugin}
  2. 提取部件号(例如:ABCDEF1234)
  3. 使用其中的唯一部件号构建替换HTML 完全取代{myplugin} ABCDEF1234,“Flux Capacitor”{/ myplugin}。
  4. 注意:在此示例中,我们将忽略“Flux Capacitor”的类别字段,因为只需要提取部件号来构建静态HTML替换。另一个程序将使用类别字段进行报告。

    静态HTML看起来像这样:

    <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//thebigpartserver.com/stuff/q?partno=**PARTNO**&link_opens_in_new_window=true&price_color=333333&title_color=0066c0&bg_color=ffffff">
        </iframe>
    

    我需要替换它:

    {myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin}
    

    与此:

    <iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//thebigpartserver.com/stuff/q?partno=ABCDEF1234&link_opens_in_new_window=true&price_color=333333&title_color=0066c0&bg_color=ffffff">
        </iframe>
    

    这可以用正则表达式完成吗?或者这会使正则表达式变得复杂吗?

    如果它被解析然后在正则表达式之外使用条件逻辑,我不需要保存指针{myplugin} ... {/ myplugin},因为$ article-&gt; text是一个字符串吗? / p>

1 个答案:

答案 0 :(得分:1)

当然,这就是你使用capturing groups

$re = '/\{myplugin\}(\w+),[^{}]+\{\/myplugin\}/';
$str = '{myplugin}ABCDEF1234,"Flux Capacitor"{/myplugin}';
$subst = '<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//thebigpartserver.com/stuff/q?partno=\\1&link_opens_in_new_window=true&price_color=333333&title_color=0066c0&bg_color=ffffff">    </iframe>';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

测试live on regex101.com

注意:我假设部件号由字母数字字符组成,后面跟一个逗号。