php – strip_tags()函数黑名单而不是白名单

前端之家收集整理的这篇文章主要介绍了php – strip_tags()函数黑名单而不是白名单前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近发现了strip_tags()函数,它接受一个字符串和一个接受的html标签列表作为参数.

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

  1. $html = '<img src="example.png">';
  2. $html = '<p><strong>This should be bold</strong></p>';
  3. $html .= '<p>This is awesome</p>';
  4. $html .= '<strong>This should be bold</strong>';
  5.  
  6. echo strip_tags($html,"<p>");

返回:

  1. <p>This should be bold</p>
  2. <p>This is awesome</p>
  3. This should be bold

因此我通过< strong>摆脱了格式化也许< em>在将来.

我想要一种黑名单的方法,而不是像白名单那样的白名单:

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

返回:

  1. <p><strong>This should be bold<strong></p>
  2. <p>This is awesome</p>
  3. <strong>This should be bold<strong>

有没有办法做到这一点?

如果您只想删除< img>标签,您可以使用DOMDocument而不是strip_tags().
  1. $dom = new DOMDocument();
  2. $dom->loadHTML($your_html_string);
  3.  
  4. // Find all the <img> tags
  5. $imgs = $dom->getElementsByTagName("img");
  6.  
  7. // And remove them
  8. $imgs_remove = array();
  9. foreach ($imgs as $img) {
  10. $imgs_remove[] = $img;
  11. }
  12.  
  13. foreach ($imgs_remove as $i) {
  14. $i->parentNode->removeChild($i);
  15. }
  16. $output = $dom->saveHTML();

猜你在找的PHP相关文章