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 = '<p>This is <b>bold</b> and <script>alert("danger")</script> text.</p>';
// Allow <b> and <i> tags while stripping all other tags
$allowed_tags = '<b><i>';
$output = strip_tags($input, $allowed_tags);
// Output the sanitized content
echo $output;
Related Questions
- What considerations should be made when using anonymous callback functions in preg_replace_callback in PHP?
- How can a PHP beginner ensure they are using the correct form submission method to avoid issues with URL parameters?
- How can beginners avoid errors like undefined index notices when working with PHP form data?