我最近发现了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>在将来.
我想要一种黑名单的方法,而不是像白名单那样的白名单:
- 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();