使用PHP和CodeIgniter将包含变量的多行字符串保存到文件中


Saving multiline strings that contain variables, into a file with PHP and CodeIgniter

我试图保存一个多行字符串,类似于纯文本:

define host {
        use                     template;
        host_name               $host_name;
        address                 46.224.2.220;
        contacts                $email;
}

,但变量如$host_name和$email必须用它们的值替换。s

我想不明白。有什么方法可以做到这一点吗?

可以使用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);

$variables在双引号中指定或使用heredoc语法(参考)时展开。所以你可以简单地输入:

$host_name = 'foo';
$email = 'bar';
$plain_text = "define host {
        use                     template;
        host_name               $host_name;
        address                 46.224.2.220;
        contacts                $email;
}";

但是,变量必须在字符串表达式之前定义。如果不是,可以使用其他答案中解释的str_replace()方法。