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

时间:2012-12-20 18:31:31

标签: php string codeigniter codeigniter-2 fwrite

我正在尝试保存多行字符串,例如纯文本

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

但变量,例如$ host_name和$ email必须替换为其值。小号

我无法弄清楚这一点。有什么方法可以达到这个目的吗?

2 个答案:

答案 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)

当用双引号或heredoc语法(reference)指定字符串时,会扩展

$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()方法。