Announcement

Collapse
No announcement yet.

parse php variables from a string?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • parse php variables from a string?

    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:
    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:
    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?
    Best Regards,
    Andy Huang

  • #2
    You need to use PHP's eval() function.

    Example:

    PHP Code:
    $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 is the PHP manual page, and the following is a working PHP example:

    PHP Code:
    <?php

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

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

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

    ?>
    Bugdar: PHP bug tracking software that is beautiful, fast, and robust.

    Comment

    widgetinstance 262 (Related Topics) skipped due to lack of content & hide_module_if_empty option.
    Working...
    X