【问题标题】:Delete some html tags just in a few cases with php只在少数情况下用php删除一些html标签
【发布时间】:2016-07-20 21:54:19
【问题描述】:

我正在使用 php,我想知道如何删除 <p class="xxx"></p> 标签

从此:

<p class="xxx">
    <a href="xxx" target="xxx">
        <figure>
            <img src="xxx"/>
            <figcaption class="xxx">
                <h1 class="xxx">Text</h1>
                <cite class="xxx">Text</cite>
            </figcaption>
        </figure>
    </a>
</p>

到这里:

<a href="xxx" target="xxx">
    <figure>
        <img src="xxx"/>
        <figcaption class="xxx">
            <h1 class="xxx">Text</h1>
            <cite class="xxx">Text</cite>
        </figcaption>
    </figure>
</a>

我想在 &lt;p&gt;&lt;a&gt;&lt;figure&gt;&lt;img/&gt;&lt;figcaption&gt;&lt;h1&gt;&lt;/h1&gt;&lt;cite&gt;&lt;/cite&gt;&lt;/figcaption&gt;&lt;/figure&gt;&lt;/a&gt;&lt;/p&gt; 时删除 &lt;p&gt;&lt;/p&gt;

我试试这个:

$html = preg_replace("'
(<p[^>]*>)([^<]*<a[^>]*>[^<]*<figure[^>]*>[^<]*<img[^>]*>[^<]*<figcaption[^>]*>[^<]*<h1[^>]*>[^<]*</h1[^>]*>[^<]*<cite[^>]*>[^<]*</cite[^>]*>[^<]*</figcaption>[^<]*[^<]*</figure>[^<]*[^<]*</a>[^<]*)(</p>)'sim", "$2", $valBody);
echo '<H1>Nuevo </H1><br>' . $html;

但我无法得到它,请你帮帮我。

【问题讨论】:

  • 不要使用正则表达式。使用DOM。与学习 DOM 并保持声带和发型完好无损相比,您将花费更多的时间在沮丧中尖叫和撕扯头发试图找出正则表达式。

标签: php html tags


【解决方案1】:

如果你想用preg_replace() 来做,我是这样做的:

<?php

$html =<<<HTML
<p class="xxx">
    <a href="xxx" target="xxx">
        <figure>
            <img src="xxx"/>
            <figcaption class="xxx">
                <h1 class="xxx">Text</h1>
                <cite class="xxx">Text</cite>
            </figcaption>
        </figure>
    </a>
</p>
HTML;

$pattern = '#(<p.+">)#';
$replace = '';
$html = preg_replace($pattern, $replace, $html);
$pattern = "#(</p>)#";
$replace = '';
$html = preg_replace($pattern, $replace, $html);
$pattern = "#(\s\s)+#";
$replace = '';
$html = preg_replace($pattern, $replace, $html);

echo '<H1>Nuevo </H1><br>' . $html;

?>

此代码给出的输出与所要求的一样:

<H1>Nuevo </H1><br><a href="xxx" target="xxx"><figure><img src="xxx"/><figcaption class="xxx"><h1 class="xxx">Text</h1><cite class="xxx">Text</cite></figcaption></figure></a>

我是一名新手程序员,这是我在 Stack Overflow 上的第一个答案。最好的问候。

【讨论】:

  • 没关系,但是删除了所有

    标签,当我找到这个标签序列时,我只想删除它们:

  • 哦。然后根据您的情况,您可以使用 XPath 获取 p 元素(如果您之前可以知道它的 xpath),然后您可以执行类似于我使用 preg_replace() 所做的操作。
猜你喜欢
  • 2019-04-10
  • 2021-08-16
  • 2020-07-05
  • 2013-08-19
  • 2021-02-09
  • 2011-04-17
  • 1970-01-01
  • 2011-11-12
  • 1970-01-01
相关资源
最近更新 更多