0

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!';
0

1 Answer 1

2

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!
Sign up to request clarification or add additional context in comments.

1 Comment

Actually it doesn't have to be eval. It is just the only one I could come up with. Ah! this works, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.