是否可以在变量中打印php变量?

I have a very simple question. But is really making me crazy.

I have a statement say:

example and example with one php variable like $loggedin_user_name

First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.

So, is it possible to print the variable within the variable? If yes, please suggest a way.

use sprintf()

$str = "example and example with one php variable like %s";

Then load it from database and fill

$out = sprintf($str, $loggedin_user_name);

If it is always the same variable name, I would suggest using

echo str_replace($fromDb, '$variableToReplace', $variableToReplace);

You can use eval function, it can be used like your example:

$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";

eval("\$str = \"$str\";");
echo $str;

Cons:

  • If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
  • In case of a fatal error in the evaluated code, the whole script exits.

You can use preg_match to find you variable name in string and then replace it with str_replace.

Best would be to concatinate a string:

$exampleWithUsername = 'example' . $loggedin_user_name;

echo $exampleWithUsername;

'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.

$name = "ABC";
$bla = "$name";
echo $bla; //ABC

Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.

You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.

But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext. Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).