[英]How do I include a yet to be defined variable inside a string? PHP
為了執行更少的數據庫查詢和清晰的代碼,我想在字符串中包含一個尚未定義的變量。 稍后在頁面中,將聲明變量並打印和評估字符串。 我該怎么做呢?
$str="This $variable is delicious";
$array=array("Apple","Pineapple","Strawberry");
foreach($array as $variable)
{
print "$str";
}
使用str_replace
。
例如:
$str = "This is [VARIABLE] is delicious";
$array = array("Apple", "Pineapple", "Strawberry");
foreach($array as $variable)
{
print str_replace('[VARIABLE]', $variable, $str);
}
你為什么不這樣做:
$array=array("Apple","Pineapple","Strawberry");
foreach($array as $variable) {
print "This $variable is delicious";
}
你可能做錯了。
學習使用模板,你永遠不會需要這些奇怪的東西。
只需將代碼分為兩部分:
你會發現你的所有代碼都變得非常整潔和可重用
$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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.