我该如何删除html标签

时间:2016-07-08 17:13:55

标签: php html tags

即时通讯使用php,我想知道如何在<p><a><img></a></p>

时删除

来自:

<p>
    <strong>Lorem</strong>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor
    <a href="xxxx" target="yyy">sit amet
    </a>, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    <img alt="" height="xxx" src="yyy" width="zzz" />
</p>

<p>
    <a href="xxx" target="_blank">
    <img alt="" height="xxx" src="yyy" width="zzz" />
    </a>
</p>

到此:

<p>
    <strong>Lorem</strong>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor
    <a href="xxxx" target="yyy">sit amet
    </a>, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    <img alt="" height="xxx" src="yyy" width="zzz" />
</p>

<a href="xxx" target="_blank">
 <img alt="" height="xxx" src="yyy" width="zzz" />
</a>

我只是想在<p></p>时删除标记<p><a><img></a></p> 我尝试过使用preg_replace();功能,但我无法得到它,请你帮助我,谢谢

3 个答案:

答案 0 :(得分:0)

您好您可以使用此功能,但请注意,只有当您<p></p>没有classi d或任何其他attribute时才会使用<p class="myclass"> }(不适用于此)。

<?php
$text ='<p>
   <a href="http://xxx" target="_blank">
       <img alt="xxx" height="xxx" src="xxx" width="xx" />
   </a>
</p>';
$text=str_ireplace('<p>','',$text);
$text=str_ireplace('</p>','',$text);
echo $text;

?>

`str_ireplace` `function` returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value.

了解更多信息,请阅读http://php.net/manual/en/function.str-ireplace.php

答案 1 :(得分:0)

<?php

$html = <<< EOFHTML
<p>
    <strong>Lorem</strong>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor
    <a href="xxxx" target="yyy">sit amet
    </a>, consectetur adipisicing elit, sed do eiusmod
</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    <img alt="" height="xxx" src="yyy" width="zzz" />
</p>

<p class="foo">
    <a href="xxx" target="_blank">
    <img alt="" height="xxx" src="yyy" width="zzz" />
    </a>
</p>
EOFHTML;


$html = preg_replace("'(<p[^>]*>)([^<]*<a[^>]*>[^<]*<img[^>]*>[^<]*</a>[^<]*)(</p>)'sim", "$2", $html);


echo $html;

答案 2 :(得分:0)

PHP 5+附带内置的DOM Parser。 PHP DOMDocument

它可用于查找,删除和添加元素。