note 50157 added to function.preg-replace
| From: | czaries at gmail dot com | Date: | Sun, 20 Feb 2005 05:52:38 +0000 |
| Subject: | note 50157 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-85259@lists.php.net to get a copy of this message | ||
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.
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+50157
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50157&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50157&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50157&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50157&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50157&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+50157&report=yes
Search -- http://master.php.net/manage/user-notes.php