簡體   English   中英

如何在字符串中包含尚未定義的變量? PHP

[英]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";
}

你可以使用printf() (或sprintf()如果你不想回應它):

$str = 'This %s is delicious';

foreach ($array as $variable) {
    printf($str, $variable);
}

使用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";
}

我認為你需要php的sprintf功能

http://php.net/manual/en/function.sprintf.php

或者它也可以使用str_replace完成

http://in.php.net/manual/en/function.str-replace.php

你可能做錯了。
學習使用模板,你永遠不會需要這些奇怪的東西。
只需將代碼分為兩部分:

  • 獲取所有必需的信息
  • 顯示常規頁面或錯誤頁面

你會發現你的所有代碼都變得非常整潔和可重用

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM