PHP使我远离eval;)字符串内的变量
出于某种原因,我现在不愿进入,我有一个像这样的字符串:
For reasons I'd rather not get into right now, I have a string like so:
<div>$title</div>
使用mysql_real_escape_string
存储在数据库中的
.
that gets stored in a database using mysql_real_escape_string
.
在正常脚本执行期间,该字符串被解析并存储在变量$string
中,然后被发送到function($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.
我也尝试过
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.
当我的心思不停地使用EVAL()
时,我决定在此发布.
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:
$var = "cute text";
echo 'this is $var';
单引号阻止解释器在字符串中查找变量.当您回显字符串变量时,情况也是如此.
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.
解决方案将是简单的str_replace
.
echo str_replace('$title', $title, $string);
但是在这种情况下,我确实建议您在文本中使用唯一的Template变量.
But in this case I really suggest Template variables that are unique in your text.