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

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

问题描述

我使用了 strip_tags() 函数,但我需要删除一些标签(以及它们的所有内容).

例如:

<p class="测试">测试 A</p><跨度>测试乙</span><div>测试 C

比方说,我需要去掉 P 和 SPAN 标签,只保留:

<div>测试 C

strip_tags 需要将您想要保留的标签作为第二个参数.

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

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

有什么想法吗?

解决方案

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

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

演示 显示它用空替换了所需的标签.

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

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

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

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

for example :

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

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 expects as a second parameter the tags that you want to KEEP.

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.

Any idea's?

解决方案

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

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆