Forum Moderators: coopster
When I run the script using php it is displayed as the text '$variable' instead of the assigned value.
Is there a way to ensure that it will be parsed as a php variable and take the value assigned to it earlier in the code?
[edited by: gargoyle1 at 8:38 pm (utc) on June 16, 2005]
So you have a database column that you are retrieving and assigning it to a variable, something like this ...
$dog = 'Bingo';
while ($row = fetching data from database result set) {
$my_text = $row['my_text'];
}
And in the variable $my_text you now have a string that maybe looks something like this ... 'My dog has a name and that name is $dog'
To parse the variable "$dog" within that text string, you have some options, eval() being one of them, but the better option is probably str_replace.
print str_replace('$dog', $dog, $my_text);
Here is a rough Idea of what I'm dealing with:
<?
$variable = 'cheeky monkey';
$example='a whole bunch of html formatting and text and this one $variable';
echo $example
?>
//Outputs: 'a whole bunch of html formatting and text and this one cheeky monkey'
This code works no problem. Its when I do this:
<?
MySQL->go get me an array
etc
$example=$row["example"]
(you get the idea here, the $example variable is stored as I had it above, but now it's in the database)
$variable='cheeky monkey';
echo $example
?>
//that THIS happens:
'a whole bunch of html formatting and text and this one $example'
I'm not sure where to put the exta '$' if that is the problem.
<?
MySQL->go get me an array
etc
$example=$row["example"]
(you get the idea here, the $example variable is stored as I had it above, but now it's in the database)$variable='cheeky monkey';
eval("\$example = \"$example\";"); //$example = "a whole text and this $variable";
echo $example
?>
However your previous code with
$example='a whole bunch of html formatting and text and this one $variable';
Will not work really. If you use single quotes ' ', then the $vars aren't parsed. You need to use double quotes: " ".
Best regards
Michal Cibor
Look at eval() here: [php.net...]
Or use the coops function. And yes, you can replace array with array
[edited by: mcibor at 9:01 pm (utc) on June 16, 2005]
Ok so let me get this straight, I would do this:
print str_replace('$variable', $variable, $example);
or if I had several things to replace, I could do this:
$find = array( bunch of variables )
$replace = array (bunch of variables2 )
print str_replace($find, $replace, $example);