2

I need a function that replace every variable_name inside '{}' with the correct variable. Something like this:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

$output = replace($string, $data);
echo $output;

//outputs: Hello my name is Johnny and I'm 20 years old.

I know there are framework/engines for this, but I don't want to have to install a bunch of files just for this.

Jon
  • 413,451
  • 75
  • 717
  • 787
user1091856
  • 2,784
  • 6
  • 28
  • 42

6 Answers6

11

You can do this most easily with the /e modifier of preg_replace:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

echo preg_replace('/{(\w+)}/e', '$data["\\1"]', $string);

See it in action.

You might want to customize the pattern that matches the replacement strings (which here is {\w+}: one or more alphanumeric characters or underscores between curly brackets). Putting it into a function is trivial.

Jon
  • 413,451
  • 75
  • 717
  • 787
2

Here you go:

$data["name"] = "Johnny";
$data["age"] = "20";

$string = "Hello my name is {name} and I'm {age} years old.";

foreach ($data as $key => $value) {
$string = str_replace("{".$key."}", $value, $string);
}

echo $string;
Kristian
  • 3,047
  • 1
  • 20
  • 45
0

I've always been a fan of strtr.

$ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
Hi Nick. The weather is Sunny.

The other advantage to this is you can define different placeholder prefix types. This is how Drupal does it; @ indicates a string to be escaped as safe to output to a web page (to avoid injection attacks). The format_string command loops over your parameters (such as @name and @weather) and if the first character is an @, then it uses check_plain on the value.

Also answered here: https://stackoverflow.com/a/36781566/224707

Community
  • 1
  • 1
Nick
  • 2,597
  • 1
  • 35
  • 56
0

You might want to have a look at the preg_replace function.

Erik
  • 212
  • 1
  • 5
0
$string = "Hello my name is {$data["name"]} and I'm {$data["age"]} years old.";

will do just what you want. If it is not suitable for you, try something like loop with the regex, like this

for ($data as $key=>$value){
    $string = preg_replace("\{$key\}", $value, $string);
}

Not tested, you might want to consult with documentation.

J0HN
  • 25,158
  • 5
  • 48
  • 84
0

You can try out vsprintf it has slightly different syntax

$string = 'hello my name is %s and I am %d years old';

$params = array('John', 29);

var_dump(vsprintf($string, $params));
//string(43) "hello my name is John and I am 29 years old" 
Nazariy
  • 5,898
  • 5
  • 35
  • 61