I've seen a lot of expressions to remove a specific tag (or many specified tags), and one to remove all but one specific tag, but I haven't found a way to remove all except many excluded (i.e. all except p, b, i, u, a, ul, ol, li
) in PHP. I'm far from good with regex, so I'd need a hand. :) Thanks!
-
1If you are not using HTML5, you may want to look into: htmlpurifier.org– JimJun 6, 2011 at 1:18
-
Or HTML_Safe package from PEAR. It has an option to set list of allowed tags.– DmitriJun 6, 2011 at 1:19
3 Answers
you can do this by usingstrip_tags
function
¶ strip_tags — Strip HTML and PHP tags from a string
strip_tags($contant,'tag you want to allow');
like
strip_tags($contant,'<code><p>');
-
8Thanks for explaining how to exclude multiple tags. The original ducumentation isn't that clear about this point.– HexodusOct 9, 2014 at 13:58
-
How to allow this tag ? I didn't get it work
<link rel="canonical" href="http://www.ann24h.com/2017/10/blog-post_89.html">
Oct 10, 2017 at 18:11 -
You can use array instead of string starting from php 7.4
$html_value = strip_tags($contente, ['code', 'p']);
Mar 19 at 17:53
strip_tags()
does exactly this.
-
It's interesting that
strip_tags
doesn't have an option to strip the content within non-allowed tags. Would have made the function more versatile. Jan 21, 2017 at 5:42 -
The php.net/strip_tags page does have a function that does just this. strip_tags_content by mariusz.tarnaski Jun 22, 2019 at 5:21
-
Why is this the accepted answer??????? strip_tags() does NOT exactly this! The title says: Strip all HTML tags, »»»»»»except«««««« allowed For strip_tags() it can be specified what to include, NOT what to exclude.– icefrontApr 11, 2020 at 17:57
-
@icefront - you need to learn to read... Quote from the Doc:
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
– RufinusApr 11, 2020 at 18:08 -
1@icefront Because it is the answer. Strig_tags accepts second parameter where we can describe tags that should be allowed. Feb 22, 2021 at 7:07
If you need some flexibility, you can use a regex-based solution and build upon it. strip_tags
as outlined above should still be the preferred approach.
The following will strips only tags you specify (blacklist):
// 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;