How do I include a yet to be defined variable inside a string? PHP

杀马特。学长 韩版系。学妹 提交于 2020-01-11 10:54:07

问题


For sake of performing less database queries and for clarity of code, I'd like include a yet to be defined variable inside a string. Later in the page, the variable will be declared and the string printed and evaluated. How do i do this?

$str="This $variable is delicious";

$array=array("Apple","Pineapple","Strawberry");

foreach($array as $variable)
{
  print "$str";
}

回答1:


You can use printf() (or sprintf() if you don't want to echo it):

$str = 'This %s is delicious';

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



回答2:


Use str_replace.

For example:

$str = "This is [VARIABLE] is delicious";
$array = array("Apple", "Pineapple", "Strawberry");

foreach($array as $variable)
{
    print str_replace('[VARIABLE]', $variable, $str);
}



回答3:


Why don't you just do:

$array=array("Apple","Pineapple","Strawberry");

foreach($array as $variable) {
    print "This $variable is delicious";
}



回答4:


I think you need php's sprintf function

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

or it can also be done using str_replace

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




回答5:


You are probably doing wrong way.
Learn to use templates and you will never need such odd things.
Just divide your code into 2 parts:

  • getting all required information
  • displaying a regular page or an error page

you will find that all your code become extremely neat and reusable




回答6:


$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;
}


来源:https://stackoverflow.com/questions/3624092/how-do-i-include-a-yet-to-be-defined-variable-inside-a-string-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!