【问题标题】:How to replace custom html tag with html code in php如何用php中的html代码替换自定义html标签
【发布时间】:2020-09-25 00:43:55
【问题描述】:

这是我的场景:在一个用 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 代码的函数。任何帮助表示赞赏。

【问题讨论】:

  • 您是否尝试过任何解决方案,出了什么问题?

标签: php html regex


【解决方案1】:

我会建议你不要将正则表达式与 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,则可以使用 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

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

【讨论】:

  • 完美运行 :-) 关于如何识别标签组并添加打开和关闭 html 标签的任何线索?非常感谢!
  • @JesúsCerezuelaZaplana 我不确定你在问什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
  • 2020-11-09
  • 2013-01-11
  • 2012-01-05
相关资源
最近更新 更多