首页  >  文章  >  后端开发  >  如何在 PHP 中去除除特定标签之外的所有 HTML 标签?

如何在 PHP 中去除除特定标签之外的所有 HTML 标签?

Susan Sarandon
Susan Sarandon原创
2024-10-17 17:34:02477浏览

How to Strip All HTML Tags Except Specific Ones in PHP?

Removing All HTML Tags Except Permitted Ones in PHP

Users frequently encounter the need to remove specific or all HTML tags from a string. However, a unique scenario arises when only certain tags are to be retained while all others are stripped. In PHP, the built-in strip_tags function provides a solution for this requirement.

Solution:

The strip_tags function allows you to select specific tags that should be exempted from removal. By passing a string of the permitted tags as the second argument, you can strip all tags except those specified:

<code class="php">$allowed_tags = '&lt;code&gt;&lt;p&gt;';
$content = strip_tags($input, $allowed_tags);</code>

In this code:

  • $input is the original HTML string.
  • $allowed_tags is a string containing the tags that should be kept (e.g., and

    ).

  • $content is the resulting string with all tags stripped except for the allowed ones.

以上是如何在 PHP 中去除除特定标签之外的所有 HTML 标签?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn