note 96316 modified in function.preg-replace by thiago
| From: | thiago@php.net | Date: | Mon, 22 Feb 2010 02:43:23 +0000 |
| Subject: | note 96316 modified in function.preg-replace by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-166239@lists.php.net to get a copy of this message | ||
I like using canned SQL queries, where specific values and/or field names are separate in some
array. However the %s place-holders of 'printf()' were tedious and error prone because of
sequence dependency. By using 'tag' replacement ( a word having some delimiter(s) around
it ) and an associative array, I was able to disconnect the canned query from the data in the array.
ex:
old style:
<?php
$sql = "SELECT %s FROM %s WHERE %s = %s";
printf($sql, data["my_field"], data["table_name"],
data["my_field"], data["field_value"] );
?>
new style:
<?php
$sql = "SELECT <my_field> FROM <table_name> FROM <my_field> =
<field_value> ";
$outsql = preg_replace("/<(\w\+)>/e","$data[\"$1\"]", $sql
);
?>
NOTE the preg_replace could be optimized to use an annonymous function instead of a
"/e" eval of the parm2 expression.
Take this a step further...
Setup your associative array to contain the output from some previous SQL, and the canned SQLs to
reference the fields of other queries. You can then chain your queries where the results of one
feeds another.
Hope this helps someone.
-- jj --
--was--
I like using canned SQL queries, where specific values and/or field names are separate in some
array. However the %s place-holders of 'printf()' were tedious and error prone because of
sequence dependency. By using 'tag' replacement ( a word having some delimiter(s) around
it ) and an associative array, I was able to disconnect the canned query from the data in the array.
ex:
old style:
$sql = "SELECT %s FROM %s WHERE %s = %s";
printf($sql, data["my_field"], data["table_name"],
data["my_field"], data["field_value"] );
new style:
$sql = "SELECT <my_field> FROM <table_name> FROM <my_field> =
<field_value> ";
$outsql = preg_replace("/<(\w\+)>/e","$data[\"$1\"]", $sql
);
NOTE the preg_replace could be optimized to use an annonymous function instead of a
"/e" eval of the parm2 expression.
Take this a step further...
Setup your associative array to contain the output from some previous SQL, and the canned SQLs to
reference the fields of other queries. You can then chain your queries where the results of one
feeds another.
Hope this helps someone.
-- jj --
http://php.net/manual/en/function.preg-replace.php