如何在php中用html代码替换自定义html标记

如何在php中用html代码替换自定义html标记,php,html,regex,Php,Html,Regex,这是我的场景:在用PHP开发的定制CMS中,我需要解析HTML字符串,搜索一些定制标记,用一些HTML代码替换它们。下面是一个澄清的例子: <h2>Some Title</h2> <p>Some text</p> [[prod_id=123]] [[prod_id=165]] // custom tag <p>More text</p> 一些标题 一些文本 [[prod_id=123][[prod_id=165]]//自定

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

<h2>Some Title</h2>
<p>Some text</p>
[[prod_id=123]] [[prod_id=165]] // custom tag
<p>More text</p>
一些标题
一些文本

[[prod_id=123][[prod_id=165]]//自定义标记 更多文本

我需要找到自定义标记并将其替换为项目的模板,因此:

<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>
一些标题
一些文本

标题产品123

标题产品165

更多文本

这将非常有用,但我需要做一些其他的事情,我需要检测标记块并在标记之前-之后添加一些代码,但每个标记块只添加一次。在本例中,所需的最终代码如下:

<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>
一些标题
一些文本

标题产品123

标题产品165

更多文本


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

我建议您不要将正则表达式与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

我没有测试这个,只是在我的头顶上做的。所以可能有一些拼写错误

您是否尝试过任何解决方案,出现了什么问题?非常有效:-)关于如何识别标记组并添加“开始者”和“结束者”html标记的任何线索?太多了@JesúsCerezuelaZaplana我不确定你在问什么?
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