note 95423 deleted from function.addslashes by danbrown
| From: | danbrown@php.net | Date: | Sun, 03 Jan 2010 01:00:47 +0000 |
| Subject: | note 95423 deleted from function.addslashes by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-164545@lists.php.net to get a copy of this message | ||
Note Submitter: phpdotnet-shaun at pressbin dot com
----
<?php
// I wrote this function because I wanted to apply addslashes
// no earlier than at the query string, but I didn't want to
// have to escape each variable separately. Note that the
// query string must be enclosed in single quotes, to prevent
// the variables from being interpreted before they get passed
// to the function.
//
// The function will detect variables of the following forms:
// $variable
// $variable[0]
// $variable[string]
function escaped($query, $function = "addslashes") {
$e = preg_replace("|\\\$([a-zA-Z_][a-zA-Z0-9_]+)\[([^\]]*?)\]|e",
"$function(\$GLOBALS[$1][$2])", $query);
$e = preg_replace("|\\\$([a-zA-Z_][a-zA-Z0-9_]+)|e",
"$function(\$GLOBALS[$1])", $e);
return $e;
}
// Example:
$first = 'Billy';
$nick = '"the Kid"';
$last = "O'Shea";
$query = 'INSERT INTO names VALUES ("$first", "$nick",
"$last")';
echo escaped($query);
// Output:
//
// INSERT INTO names VALUES ("Billy", "\"the Kid\"",
"O\'Shea")
?>