How can one efficiently remove specific HTML elements, such as line breaks, only in certain contexts using PHP?

To efficiently remove specific HTML elements, such as line breaks, only in certain contexts using PHP, you can use the strip_tags() function along with a whitelist of allowed tags. By specifying which tags are allowed, you can effectively remove unwanted elements while keeping others intact.

// Define the HTML content
$html = "<p>This is some text with <br>line breaks</p>";

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

// Remove unwanted elements
$cleaned_html = strip_tags($html, $allowed_tags);

// Output the cleaned HTML
echo $cleaned_html;