For reasons I'd rather not get into right now, I have a string like so:
<div>$title</div>
that gets stored in a database using mysql_real_escape_string
.
During normal script execution, that string gets parsed and stored in a variable $string
and then gets sent to a function($string)
.
In this function, I am trying to:
function test($string){
$title = 'please print';
echo $string;
}
//I want the outcome to be <div>please print</div>
This seems like the silliest thing, but for the life of me, I cannot get it to "interpret" the variables.
I've also tried,
echo html_entity_decode($string);
echo bin2hex(html_entity_decode($string)); //Just to see what php was actually seeing I thought maybe the $ had a slash on it or something.
I decided to post on here when my mind kept drifting to using EVAL()
.
This is just pseudocode, of course. What is the best way to approach this?
I don't think there is a way to get that to work. You are trying something like this:
The single quotes are preventing the interpreter from looking for variables in the string. And it is the same, when you echo a string variable.
The solution will be a simple
str_replace
.But in this case I really suggest Template variables that are unique in your text.
You just don't do that, a variable is a living thing, it's against its nature to store it like that, flat and dead in a string in the database.
If you want to replace some parts of a string with the content of a variable, use
sprintf()
.Example
Then use it with:
will result in:
Your example is a bit abstract. But it seems like you could do pretty much what the template engines do for these case:
Now actually,
/e
is pretty much the same as using eval. But at least this only replaces actual variable names. Could be made a bit more sophisticated still.If you know that the variable inside the div is
$title
, you canstr_replace
it.If you don't know the variables in the string, you can use a regex to get them (I used the regex from the PHP manual).