PDA

View Full Version : parse php variables from a string?


Andy Huang
Sat 6th Nov '04, 10:37pm
Hi all;
I know this must be a ridiculously easy question that I'm simply overseeing due to tiredness, but say I have a string "This is my long string {$PAGEVAR['abc']}", normally, if I have $PAGEVAR['abc'] defined as "for testing.", when I echo it, it should give output: "This is my long string for testing."

Code:

<?php
$PAGEVAR['abc'] = "for testing.";
$foo = "This is my long string {$PAGEVAR['abc']}";
print $foo;
?>

Output:
This is my long string for testing.

Right now, the above works no problem. But if I were to obtain the $foo from a query and do the same thing, it doesn't seem to want to print it?

Code:

<?php
$database = new database($username, $password); // its my nifty little database class...

$PAGEVAR['abc'] = "for testing.";
$result = $database->execute("SELECT string FROM test WHERE sid = 1;");
$row = mysql_fetch_row($result);
$foo = $row['string']; // store "This is my long string {$PAGEVAR['abc']}"
print $foo;
?>

Output:
This is my long string {$PAGEVAR['abc']}.

Am I doing something wrong? Why is it not appearing properly?

daemon
Sun 7th Nov '04, 12:20am
You need to use PHP's eval() function.

Example:


$mysql_row = $DB_sql->query_first("SELECT * FROM cows WHERE eatsgrass = 1"); // get me all the cows who have eaten grass
eval('$row_done = "' . addslashes($mysql_row['likescowbell']) . '";'); // this row entry contains PHP variables, and PHP evaluates it -- make sure we addslashes() because if it has a double quote we'll get a parse error
echo $row_done; // Print out the evalutaed 'likescowbell' row


PHP's eval() function is a pain most of the time. What eval() does is it takes unevalutaed PHP code and evaluates it. You need to think of the eval() function as simply placing a block of PHP code equal to something (or running it through a function).

It's a hard function to explain, you should play with it. Here (http://php.net/eval) is the PHP manual page, and the following is a working PHP example:

<?php

$test = 'cow';
$moo = '"$test" is a poopy';

eval('$output = "' . addslashes($moo) . '";');
echo $output;

// OR:
//eval('echo("' . addslashes($moo) . '");');

?>