Are there any specific functions in PHP that can help preserve certain HTML tags while stripping others?

When working with user-generated content, you may want to preserve certain HTML tags (such as <b>, <i>, <a>, etc.) while stripping others (such as <script>, <style>, etc.) to prevent security vulnerabilities or maintain the desired formatting. One way to achieve this is by using PHP's strip_tags() function with the exception parameter to specify which tags to allow.

// Input string with HTML content
$input = &#039;&lt;p&gt;This is &lt;b&gt;bold&lt;/b&gt; and &lt;script&gt;alert(&quot;danger&quot;)&lt;/script&gt; text.&lt;/p&gt;&#039;;

// Allow &lt;b&gt; and &lt;i&gt; tags while stripping all other tags
$allowed_tags = &#039;&lt;b&gt;&lt;i&gt;&#039;;
$output = strip_tags($input, $allowed_tags);

// Output the sanitized content
echo $output;