...

View Full Version : problem with nested variables



The Reverend
11-30-2006, 09:17 AM
Okay, here's the problem. I have a string I retrieve from the database that contains several PHP variables, I want to evaluate it and have the variables filled in, I'm just not sure how to do this.

This is the string I'm retrieving for example:


<b>$test</b>

before I retrieve it I declare the variable $test, but when I print it out it comes out as this "$test", and doesn't evaluate. How do I do this? I tried using the eval() function and it still doesn't change the output. This is a simplified example of what I'm actually doing to make it easier to solve, if anyone can help I'd appreciate it.

NancyJ
11-30-2006, 01:03 PM
$test = "bob";
$string = '<b>$test</b>';

eval("\$result = ".$string);
echo $result;


Without seeing your code this is the best I can do - I havent tried it but it should work

Tyree
11-30-2006, 02:17 PM
This probably isn't as simple as I'm seeing it...but are you wrapping your php in "<?php ?>" ? The example you show is not going to do anything but what you said it does.

Here's two examples of ways to display the value of $test:


<?php
$test = "blah";
?>

<b><?php print $test; ?></b>


OR



<?php
$test = "blah";

print "<br>".$test."</br>";
?>


You can't mix html and php without telling the browser what is what.

Hope that helps!

The Reverend
11-30-2006, 06:48 PM
It's a little more complicated than that, I tried using eval and it doesn't work. Here's a little more complicated version to give you a better idea.


<?php
$test = 'test';

$result = mysql_query("SELECT `field` FROM `table` WHERE id='1' LIMIT 1");
while($row = mysql_fetch_assoc($result))
{
$string = $row['field'] //this value retrived is "<b>$test</b>"
}
echo $string;

//output is "<b>$test</b>", not "<b>test</b>" like I want

?>

Again, this is a simplified example of what I'm doing.

ralph l mayo
11-30-2006, 07:32 PM
eval does it, you've just got to make sure the evaled string ends up with double quotes around the target string.



$test = 'asdf';
$othervar = 'qwerty';
$string = '<b>$test</b><i>$othervar</i>';

eval('$replaced_string = "' . $string . '";');
echo $replaced_string; # <b>asdf</b><i>qwerty</i>


A better approach I think would be to use a table:



function make_replacements($string, $replacements)
{
foreach ($replacements as $tag=>$value)
{
$string = str_replace($tag, $value, $string);
}
return $string;
}
$string = '<b>$test</b><i>$othervar</i>';
static $replacements = array(
'$test' => 'asdf',
'$othervar' => 'qwerty'
);
echo make_replacements($string, $replacements); # <b>asdf</b><i>qwerty</i>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum