Tags
Asked 2 years ago
9 Jun 2021
Views 212
debugger

debugger posted

strip_tags all except some and remove styling from in php ?

strip_tags all except some and remove styling from in php ?
noob

noob
answered Apr 25 '23 00:00

To remove all HTML tags from a string in PHP, except for some specific tags, and also remove any styling, you can use the strip_tags() function along with the allowed_tags parameter and then use the htmlspecialchars () function to encode any remaining HTML entities. Here's an example:



// Input string with HTML tags and styling
$input_string = '<p style="color: red">This is <strong>bold text</strong> and <em>italic text</em>.</p>';

// Define the allowed tags
$allowed_tags = '<strong><em>';

// Remove all HTML tags except allowed tags and their attributes
$filtered_string = strip_tags($input_string, $allowed_tags);

// Encode any remaining HTML entities
$filtered_string = htmlspecialchars($filtered_string, ENT_QUOTES, 'UTF-8');

// Output the filtered string
echo $filtered_string;

In this example, the output will be:



This is <strong>bold text</strong> and <em>italic text</em>
.
Here, the strip_tags () function removes all HTML tags except for the < strong > and < em > tags because they are included in the allowed_tags parameter. The htmlspecialchars () function then encodes any remaining HTML entities, such as the < and > characters. Finally, the filtered string is outputted.
Post Answer