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();