xam
xam

Reputation: 452

process embedded variable within a string using PHP

How do I process a variable that was embedded within a string? The string came from a database, so here is an example:

1: $b='World!';
2: $a='Hello $b';   #note, I used single quote purposely to emulate the string was originally from the database (I know the different of using ' or ").
3: eval($c=$a.";"); #I know this would not work, but trying to do $c="Hello $b";
#With line 3 PHP code, I am trying get the outcome of $c='Hello World!';

Upvotes: 0

Views: 45

Answers (1)

Dekel
Dekel

Reputation: 62536

If you want to eval the line of code $c='Hello World'; you should have a string that when echoed you will get exactly that: $c="Hello $b";.

So - for start, your $c variable should be inside a string (and not as a variable);

'$c'

Next - the = sign should be inside a string (and not as part of the php code, otherwise the preprocessor will try to assign the value on the right to the variable on the left.

How about this one:

$new_str = '$c=' . $a . ';';
echo $new_str;

Now you can see that the value inside $new_str is actually:

$c=Hello $b;

Which is not a valid php code (because you don't have Hello in PHP. What you actually want is to have the Hello $b part inside a double-quote:

$new_str = '$c="' . $a . '";';

And only now you can eval this.

So your final code should look like:

$b='World!';
$a='Hello $b';

eval('$c="' . $a . '";');
echo $c; // Hello World!

Upvotes: 2

Related Questions