我最近发现了一个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>");
Run Code Online (Sandbox Code Playgroud)
返回:
<p>This should be bold</p>
<p>This is awesome</p>
This should be bold
Run Code Online (Sandbox Code Playgroud)
因此我通过<strong>也许<em>将来摆脱了格式化.
我想要一种黑名单的方法,而不是像白名单那样的白名单:
echo blacklist_tags($html,"<img>");
Run Code Online (Sandbox Code Playgroud)
返回:
<p><strong>This should be bold<strong></p>
<p>This is awesome</p>
<strong>This should be bold<strong>
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
如果您只想删除<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();
Run Code Online (Sandbox Code Playgroud)