如何替换自定义html标签与html代码在php


How to replace custom html tag with html code in php

这是我的场景:在用PHP开发的自定义CMS中,我需要解析HTML字符串,搜索一些自定义标记,并用一些HTML代码替换它们。下面是一个澄清的例子:

<h2>Some Title</h2>
<p>Some text</p>
[[prod_id=123]] [[prod_id=165]] // custom tag
<p>More text</p>

我需要找到自定义标签,并用项目的模板替换它们,结果是:

<h2>Some Title</h2>
<p>Some text</p>
<!--Start Product123-->
<p>Title Product 123</p>
<!--End Product123-->
<!--Start Product165-->
<p>Title Product 165</p>
<!--End Product165-->
<p>More text</p>

这将是非常有帮助的,但我需要做别的事情,我需要检测标记块,并在标记之前-之后添加一些代码,但每个标记块只有一次。在本例中,所需的最终代码类似于:

<h2>Some Title</h2>
<p>Some text</p>
<div><!-- Here the start of the block -->
<!--Start Product123-->
<p>Title Product 123</p>
<!--End Product123-->
<!--Start Product165-->
<p>Title Product 165</p>
<!--End Product165-->
</div><!-- Here the end of the block -->
<p>More text</p>

对我来说,完美的解决方案是用原始HTML代码作为参数的函数,并返回最终的HTML代码。任何帮助都是感激的。

我建议你不要将Regex与HTML一起使用,这会导致很多问题。相反,你可以做一些事情,比如存储文章的文本/内容,然后只处理它们。

但是为了完整起见,您可以这样使用:

$html = preg_replace_callback("/'['[prod_id=('d+)']']/",
    function($matches)
    {
        $prod_id = $matches[1];
        return '<p>Title Product ' . $prod_id . '</p>';
    },
    $html); // where $html is the html you want to process

如果你没有"have"然后你可以使用ob_start()ob_get_clean()

ob_start();
?>
<h2>Some Title</h2>
<p>Some text</p>
[[prod_id=123]] [[prod_id=165]] // custom tag
<p>More text</p>
<?php
$html = ob_get_clean();
// do the regex_replace_callback here

我没有测试过这个,只是在我的头上做了。所以可能会有一些错别字!