note 21151 added to function.htmlspecialchars
| From: | juadielon_NOSPAM at hotmail dot com | Date: | Wed, 01 May 2002 01:09:03 +0000 |
| Subject: | note 21151 added to function.htmlspecialchars | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-30033@lists.php.net to get a copy of this message | ||
I was trying to retrieve information from a database to display it into the browser. However it did
not work as I was expecting. For instance double quotes () and single quotes () were
conflicting in HTML in an INPUT selector.
The first approach to solve this was to use htmlspecialchars to convert special characters to HTML
entities to display the input box with its value.
$encode=htmlspecialchars($str, ENT_QUOTES);
However, the result was having HTML entities with a \ (backslash) preceding it (escape characters).
For instance ampersand (&) becomes \& displaying \& and double quotes becomes
\" displaying \
So the final solution was to replace first any \ (backslash) and then ask htmlspecialchars to make
the conversion.
$encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);
Try this example to see it your self.
<form action="<?php echo $PHP_SELF; ?>">
<input type="text" name="str" size="20" value="">
<input type="submit" value="Submit">
<br>
<?php
if (!empty($str)) {
$encoded=htmlspecialchars(str_replace('\\', '', $str), ENT_QUOTES);
echo "<br><p>Result: <b>".$encoded."</b>. It should be the
same you just typed</p>";
echo "<p>But source code is transformed
to:<b><xmp>".$encoded."</xmp></b></p>";
// I know, I know <xmp> is deprecated in HTML 4 but was easy to use this time to display
result.
}
?>
</form>
Hope this will helps someone.
--
http://www.php.net/manual/en/function.htmlspecialchars.php
http://master.php.net/manage/user-notes.php?action=edit+21151
http://master.php.net/manage/user-notes.php?action=delete+21151
http://master.php.net/manage/user-notes.php?action=reject+21151