How can HTML be used to display special characters like \n and \r in PHP output?

Special characters like \n (newline) and \r (carriage return) in PHP output can be displayed using HTML entities. By using htmlentities() function in PHP, these special characters can be converted to their respective HTML entities, which will be displayed correctly in the browser. This ensures that the special characters are not interpreted as literal newlines or carriage returns in the output.

<?php
$text = "This is a text with \n newline and \r carriage return characters.";
echo htmlentities($text);
?>