How to format special characters
An example that uses special characters
The text entered by the user
Welcome to <i>PHP</i> and MySQL!
PHP that converts special characters to character entities
<?php
$comment = $_POST['comment'];
$comment = htmlspecialchars($comment);
?>
<p><?php echo("$comment"); ?></p>
The data displayed in the browser
Welcome to <i>PHP</i> and MySQL!
A double-encoded less than character entity (<)
A statement that prevents double encoding
$comment = htmlspecialchars($comment, ENT_COMPAT, 'ISO-8859-1', false);
How to format line breaks
The text entered into the text area
Welcome to
PHP and MySQL!
PHP that converts line break characters to HTML line break tags
<php
$comment = filter_input(INPUT_POST, 'comment');
$comment = nl2br($comment, false); // usetags <br>, not &;t'br /> tags
?>
The data displayed in the browser
Welcome to
PHP and MySQL!
- An HTML character entity lets you display some special characters on a web page.
- The htmlspecialchars() function converts some special characters into character entities. This provides a way to display special characters and helps to guard against XSS attacks. You can also use this function to prevent double encoding of character entities.
- The nl2br() function converts new line characters in a string to HTML tags. This lets you display the line breaks on a web page.
Back