strip_tags()函数列入黑名单而非白名单 [英] strip_tags() function blacklist rather than whitelist

查看:87
本文介绍了strip_tags()函数列入黑名单而非白名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了strip_tags()函数,该函数以字符串和可接受的html标签列表作为参数.

I recently discovered the strip_tags() function which takes a string and a list of accepted html tags as parameters.

让我们说我想摆脱字符串中的图像,这是一个示例:

Lets say I wanted to get rid of images in a string here is an example:

$html = '<img src="example.png">';
$html = '<p><strong>This should be bold</strong></p>';
$html .= '<p>This is awesome</p>';
$html .= '<strong>This should be bold</strong>';

echo strip_tags($html,"<p>");

返回此:

<p>This should be bold</p>
<p>This is awesome</p>
This should be bold

因此,将来我不再通过<strong>甚至也许是<em>进行格式化.

consequently I gotten rid of my formatting via <strong> and perhaps <em> in the future.

我想要一种将类似黑名单而不是白名单的方法:

I want a way to blacklist rather than whitelist something like:

echo blacklist_tags($html,"<img>");

返回:

<p><strong>This should be bold<strong></p>
<p>This is awesome</p>
<strong>This should be bold<strong>

有什么办法吗?

推荐答案

如果只希望删除<img>标签,则可以使用DOMDocument代替strip_tags().

If you only wish to remove the <img> tags, you can use DOMDocument instead of strip_tags().

$dom = new DOMDocument();
$dom->loadHTML($your_html_string);

// Find all the <img> tags
$imgs = $dom->getElementsByTagName("img");

// And remove them
$imgs_remove = array();
foreach ($imgs as $img) {
  $imgs_remove[] = $img;
}

foreach ($imgs_remove as $i) {
  $i->parentNode->removeChild($i);
}
$output = $dom->saveHTML();

这篇关于strip_tags()函数列入黑名单而非白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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