PHP:strip_tags-仅删除某些标签(及其内容)? [英] PHP: strip_tags - remove only certain tags (and their contents)?

查看:321
本文介绍了PHP:strip_tags-仅删除某些标签(及其内容)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用strip_tags()函数,但是我需要删除一些标签(及其所有内容).

I use the strip_tags() function but I need to remove some tags (and all of their contents).

例如:

<div>
  <p class="test">
    Test A
  </p>
  <span>
    Test B
  </span>
  <div>
    Test C
  </div>
</div>

比方说,我需要摆脱P和SPAN标签,而只保留:

Let's say, I need to get rid of the P and SPAN tags, and only keep :

<div>
  <div>
    Test C
  </div>
</div>

strip_tags希望将要保留的标签作为第二个参数.

strip_tags expects as a second parameter the tags that you want to KEEP.

在此特定示例中,我可以使用striptags($html, "<div>"); 但是我要抓取的html和需要删除的标签一直都不同.

In this particular example I could use striptags($html, "<div>"); but the html I'm scraping and the tags that need to be removed are different all the time.

我搜索了几个小时的适合我需要的功能,但找不到任何有用的功能.

I searched for hours for a function that suits my needs, but couldn't find anything useful.

有什么主意吗?

推荐答案

使用正则表达式.这样的事情应该起作用:

Use a regular expression. Something like this should work:

$tags = array( 'p', 'span');
$text = preg_replace( '#<(' . implode( '|', $tags) . ')>.*?<\/$1>#s', '', $text);

演示显示了它完全替换了所需的标签.

The demo shows it replacing the desired tags with nothing.

请注意,您可能需要对其进行更多调整,以补偿标签中的空白或示例中未显示的其他未知内容.

Note that you may need to tweak it more, say, to compensate for whitespace within the tags, or other unknowns that your example does not demonstrate.

以下是用于捕获具有或不具有属性的标签的正则表达式:

Here is the regex to use to capture tags with or without attributes:

'#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?<\/$1>#s'

这篇关于PHP:strip_tags-仅删除某些标签(及其内容)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆