note 50157 deleted from function.preg-replace by nlopess
| From: | nlopess@php.net | Date: | Sun, 20 Feb 2005 13:05:57 +0000 |
| Subject: | note 50157 deleted from function.preg-replace by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-85278@lists.php.net to get a copy of this message | ||
Note Submitter: czaries at gmail dot com
Reason: useless
----
Building even further on the example of direct variable replacement given by daniil, it is sometimes
very helpful to allow the user to build their own custom data output from MySQL table data or an
array with certian keys. In this case (or in similar cases), you would replace the user's
input with the same name as an array key to replace it with the proper value. With a little
modification, I came up with something like this.
This example uses Smarty (http://smarty.php.net) style custom variables.
Example: {$name} instead of the previous example's [name]
<?php
$output = "
<p>{$title} posted by {$user}</p>
<p>
{$content}
</p>
";
$sql = mysql_query("SELECT * FROM news");
while($row = mysql_fetch_array($sql)) {
$newsitem = preg_replace("/\{\\$(\w+)\}/e", "\$row['\\1']", $output);
echo $newsitem;
}
?>
The above code takes the value between {$ and } and uses it as an array key. So in our example
"{$title}" would be replaced with "$row['title']", and would print the
value for the column "title" for the current mysql record.
This method also greatly improves security since users can now no longer print out any variable they
want, but instead only those within the predefined array, in this case $row.