note 68322 modified in function.htmlentities by danbrown

From: Date: Sun, 17 May 2009 16:57:36 +0000
Subject: note 68322 modified in function.htmlentities by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154918@lists.php.net to get a copy of this message
The data returned by a text input field is ready to be used in a data base query when enclosed in single quotes, e.g. <?php mysql_query ("SELECT * FROM Article WHERE id = '$data'"); ?> But you will get problems when writing back this data into the input field's value, <?php echo "<input name='data' type='text' value='$data'>"; ?> because hmtl codes would be interpreted and escape sequences would cause strange output. The following function may help: <?php function deescape ($s, $charset='UTF-8') { // don't interpret html codes and don't convert quotes $s = htmlentities ($s, ENT_NOQUOTES, $charset); // delete the inserted backslashes except those for protecting single quotes $s = preg_replace ("/\\\\([^'])/e", '"&#" . ord("$1") . ";"', $s); // delete the backslashes inserted for protecting single quotes $s = str_replace ("\\'", "&#" . ord ("'") . ";", $s); return $s; } ?> Try some input like: a'b"c\d\'e\"f\\g&x#27;h to test ... --was-- Unfortunately, there are differences between what is shown in the preview window and what is shown on the web site; thus, the extreme number of backslashes in my former note. The corrected note: The data returned by a text input field is ready to be used in a data base query when enclosed in single quotes, e.g. <?php mysql_query ("SELECT * FROM Article WHERE id = '$data'"); ?> But you will get problems when writing back this data into the input field's value, <?php echo "<input name='data' type='text' value='$data'>"; ?> because hmtl codes would be interpreted and escape sequences would cause strange output. The following function may help: <?php function deescape ($s, $charset='UTF-8') { // don't interpret html codes and don't convert quotes $s = htmlentities ($s, ENT_NOQUOTES, $charset); // delete the inserted backslashes except those for protecting single quotes $s = preg_replace ("/\\\\([^'])/e", '"&#" . ord("$1") . ";"', $s); // delete the backslashes inserted for protecting single quotes $s = str_replace ("\\'", "&#" . ord ("'") . ";", $s); return $s; } ?> Try some input like: a'b"c\d\'e\"f\\g&x#27;h to test ... http://php.net/manual/en/function.htmlentities.php

« previous php.notes (#154918) next »