gpt4 book ai didi

php - strip_tags() 功能黑名单而不是白名单

转载 作者:可可西里 更新时间:2023-11-01 13:18:23 29 4
gpt4 key购买 nike

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

假设我想摆脱字符串中的图像,这是一个例子:

$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> future 。

我想要一种将黑名单而不是白名单的方法,例如:

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

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

关于php - strip_tags() 功能黑名单而不是白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072327/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com