简体   繁体   中英

How can I use a variable variable in PHP?

Here is what I am trying to do:

<?php
    $my_str = "My String";
    $str = "%my_str";

    $str = str_replace("%", "$", $str);

    echo $str;
?>

The above code prints '$my_str' to the screen. But I want it to print 'My String', as in the actual value of the variable $my_str

Anyone know how to do this?

The reason I want this is because I'm in the process of writing my own, very basic, parsing language so I kinda need this to be functional before I can continue.

$my_str = 'My String';
$str    = 'my_str';

echo $$str;

This construction is called a variable variable .

eval is not necessary. Just get rid of the % and use $$str

<?php
    $my_str = "My String";
    $str = "%my_str";

    $str = str_replace("%", "", $str);

    echo $$str;
?>

You could search and replace the %var patterns using preg_replace and the e modifier, which makes the replacement being evaluated:

<?php
    $my_str = "My String";
    $str = "Foo %my_str bar";

    $str = preg_replace("/%([A-Za-z_]+)/e", "$\\1", $str);

    echo $str;
?>

Here preg_replace will find %my_str , \\1 contains my_str and "$\\\\1" (the backslash needs to be escaped) becomes the value of $my_str.

However, it would maybe be cleaner to store your replacement strings in an associative array:

<?php
    $replacements = array(
        "my_str" => "My String",
    );
    $str = "Foo %my_str bar";

    $str = preg_replace("/%([A-Za-z_]+)/e", '$replacements["\\1"]', $str);

    echo $str;
?>

尝试:

echo $$str;

PHP automatically parses and expands variables within double-quoted strings :

<?php
    $my_str = "My String";
    $str = "{$my_str}";

    echo $str;
?>

Outputs:

My String

How about using a regex with the e modifier

$str = preg_replace("/%([a-zA-Z0-9_]+)/e", '$\1', $str);

(This is untested, but should work)

The behaviour you see is not surprising - expansion of variables ("interpolation") is performed on only string literals, rather than variables. If it wasn't, then it would be a large security hole (any instance of a string with $ in it that your code used would suddenly be revealing variables).

You can try and fix this using eval, as in

eval ("\$str = \"" . str_replace("%", "\$", $str) . "\"");

but this pretty dangerous - if your string is from the user, then can make $str something like

"; system("rm -rf /"); $x = "

and suddenly, you're in trouble. The best solution, I believe, will be to parse out variables using your favourite methods (stripos and substring, or something more), then replace each one by hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM