0

我正在尝试以纯文本格式保存多行字符串,如下所示:

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

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

我想不通。有什么办法可以做到这一点?

4

2 回答 2

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);
于 2012-12-20T19:00:31.500 回答
1

$variables当字符串用双引号或使用 heredoc 语法 ( reference ) 指定时,将展开。所以你可以简单地做:

$host_name = 'foo';
$email = 'bar';

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

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

于 2012-12-21T00:38:17.307 回答