为了执行更少的数据库查询和清晰的代码,我想在字符串中包含一个尚未定义的变量。稍后在页面中,将声明变量并打印和评估字符串。我该怎么做?
$str="This $variable is delicious";
$array=array("Apple","Pineapple","Strawberry");
foreach($array as $variable)
{
print "$str";
}
答案 0 :(得分:13)
如果您不想回复它,可以使用printf()
(或sprintf()
):
$str = 'This %s is delicious';
foreach ($array as $variable) {
printf($str, $variable);
}
答案 1 :(得分:0)
使用str_replace
。
例如:
$str = "This is [VARIABLE] is delicious";
$array = array("Apple", "Pineapple", "Strawberry");
foreach($array as $variable)
{
print str_replace('[VARIABLE]', $variable, $str);
}
答案 2 :(得分:0)
你为什么不这样做:
$array=array("Apple","Pineapple","Strawberry");
foreach($array as $variable) {
print "This $variable is delicious";
}
答案 3 :(得分:0)
答案 4 :(得分:0)
你可能做错了。
学习使用模板,你永远不会需要这些奇怪的东西
只需将代码分为两部分:
您会发现所有代码都变得非常整洁且可重复使用
答案 5 :(得分:-2)
$str='This $variable is delicious'; // so no variable interpolation is performed
$array=array("Apple","Pineapple","Strawberry");
foreach($array as $variable)
{
// Warning! This is a very bad idea!
// Using eval or system might create vulnerabilities!
eval('$str="' . $str . '";');
print $str;
}