0

次のような複数行の文字列をプレーンテキストで保存しようとしています:

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

ただし、$host_name や $email などの変数は、それらの値に置き換える必要があります。s

私はこれを理解できませんでした。これを達成する方法はありますか?

4

2 に答える 2

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()そうでない場合は、他の回答で説明されている方法を使用できます。

于 2012-12-21T00:38:17.307 に答える
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 に答える