【问题标题】:Strip all HTML tags, except allowed去除所有 HTML 标签,允许的除外
【发布时间】:2011-09-08 23:24:46
【问题描述】:

我见过很多删除特定标签(或许多指定标签)和one to remove all but one specific tag 的表达式,但我还没有找到一种方法来删除除许多排除之外的所有内容(即除p, b, i, u, a, ul, ol, li 之外的所有内容)在 PHP 中。我对正则表达式还不够好,所以我需要帮助。 :) 谢谢!

【问题讨论】:

  • 如果您不使用 HTML5,您可能需要查看:htmlpurifier.org
  • 或来自 PEAR 的 HTML_Safe 包。它有一个选项来设置允许的标签列表。

标签: php html regex tags


【解决方案1】:

你可以使用strip_tags函数来做到这一点

strip_tags — 从字符串中去除 HTML 和 PHP 标记

 strip_tags($contant,'tag you want to allow');

喜欢

  strip_tags($contant,'<code><p>');

【讨论】:

  • 感谢您解释如何排除多个标签。原始文件对这一点不是很清楚。
  • 如何允许这个标签?我没有得到它的工作&lt;link rel="canonical" href="http://www.ann24h.com/2017/10/blog-post_89.html"&gt;
【解决方案2】:

strip_tags() 正是这样做的。

【讨论】:

  • 有趣的是strip_tags 没有选项可以去除不允许的标签中的内容。会使功能更加通用。
  • php.net/strip_tags 页面确实有一个功能可以做到这一点。 strip_tags_content by mariusz.tarnaski
  • 为什么这是公认的答案?????? strip_tags() 不完全是这个!标题说:去除所有 HTML 标签,»»»»»»除了«««««« 允许 对于 strip_tags(),它可以指定要包含的内容,而不是要排除的内容。
  • @icefront - 你需要学习阅读...引用文档:You can use the optional second parameter to specify tags which should not be stripped. These are either given as string, or as of PHP 7.4.0, as array
  • @icefront 因为这是答案。 Strig_tags 接受第二个参数,我们可以在其中描述应该允许的标签。
【解决方案3】:

如果您需要一些灵活性,您可以使用基于正则表达式的解决方案并在此基础上进行构建。如上所述的strip_tags 仍应是首选方法。

以下内容将仅去除您指定的标签(黑名单):

// tags separated by vertical bar
$strip_tags = "a|strong|em";

// target html
$html = '<em><b>ha<a href="" title="">d</a>f</em></b>';

// Regex is loose and works for closing/opening tags across multiple lines and
// is case-insensitive

$clean_html = preg_replace("#<\s*\/?(".$strip_tags.")\s*[^>]*?>#im", '', $html);

// prints "<b>hadf</b>";
echo $clean_html;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2020-07-11
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多