0

I'm trying to save a multiline string, something like this in plain text:

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

but variables e.g. $host_name and $email must be replaced with their values. s

I couldn't figure this out. any way to achieve this?

Zim3r
  • 580
  • 2
  • 14
  • 36
  • 1
    Regular expression replacement preg_replace() - if you have tried that, what's wrong with it? – Mats Petersson Dec 20 '12 at 18:36
  • Thank you, actually I don't know how to keep that spacing and the shape similar to how it is displayed above. – Zim3r Dec 20 '12 at 18:53
  • I don't see why preg_/str_replace would change that - assuming you read it in right - which is a different matter that you didn't ask about, nor am I sure about the answer. – Mats Petersson Dec 20 '12 at 19:01
  • I think I did something wrong and your right. I'll try again. Thanks – Zim3r Dec 20 '12 at 19:04

2 Answers2

1

You can use 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);
user1190992
  • 669
  • 3
  • 8
1

$variables are expanded when the string is specified in double quotes or with heredoc syntax (reference). So you can simply do:

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

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

However, the variables have to be defined before the string expression. If they're not, you can use the str_replace() method explained in other answers.

Gras Double
  • 15,901
  • 8
  • 56
  • 54