简体   繁体   English

如何用php中的html代码替换自定义html标签

[英]How to replace custom html tag with html code in php

This is my scenario: In a custom CMS developed in PHP, I need to parse HTML string searching some custom tags to replace them with some HTML code.这是我的场景:在用 PHP 开发的自定义 CMS 中,我需要解析 HTML 字符串,搜索一些自定义标签以将它们替换为一些 HTML 代码。 Here is an example for clarifying:这是一个澄清的例子:

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

I need to find the custom tags and replace them with the template of the item, as a result:我需要找到自定义标签并将它们替换为项目的模板,结果:

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

This would be very helpful, but I need to do something else, I need to detect blocks of tags and add some code before - after the tags, but only once per block of tags.这将非常有帮助,但我需要做其他事情,我需要检测标签块并在标签之前 - 之后添加一些代码,但每个标签块只能添加一次。 In this example, the final code needed would be something like:在此示例中,所需的最终代码类似于:

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

The perfect solution for me would be a function with the original HTML code as argument, and returning the final html code.对我来说,完美的解决方案是以原始 HTML 代码作为参数的函数,并返回最终的 html 代码。 Any help is appreciated.任何帮助表示赞赏。

I will advise you to not use Regex along with HTML, this can result in a lot of problems.我建议您不要将 Regex 与 HTML 一起使用,这会导致很多问题。 Instead do something like where you store the text/content of articles and then only process that.而是做一些像你存储文章的文本/内容的地方,然后只处理它。

But for the sake of completeness, you can use something like this:但为了完整起见,您可以使用以下内容:

$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

If you don't "have" the HTML, then you can use ob_start() and ob_get_clean() .如果您没有“拥有”HTML,那么您可以使用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

I haven't tested this, just did it on top of my head.我没有测试过这个,只是在我的头顶上做了。 So there might be some typos!所以可能有错别字!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM