我正在尝试保存多行字符串,例如纯文本:
define host {
use template;
host_name $host_name;
address 46.224.2.220;
contacts $email;
}
但变量,例如$ host_name和$ email必须替换为其值。小号
我无法弄清楚这一点。有什么方法可以达到这个目的吗?
答案 0 :(得分:1)
您可以使用str_replace
$plain_text = "define host {
use template;
host_name $host_name;
address 46.224.2.220;
contacts $email;
}";
$find = array("$host_name", "$email");
$replace = array($host_name, $email);
$new_plain_text = str_replace($find, $replace, $plain_text);
答案 1 :(得分:1)
$variables
。所以你可以这样做:
$host_name = 'foo';
$email = 'bar';
$plain_text = "define host {
use template;
host_name $host_name;
address 46.224.2.220;
contacts $email;
}";
但是,必须在字符串表达式之前定义变量。如果不是,您可以使用其他答案中解释的str_replace()
方法。