How to replace placeholders with actual values?

I need a function that replaces every variable name inside '{}' with the correct variable. Something like that:

$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 that there is a framework / engines for this, but I do not want to install a bunch of files for this.

+1
source share
6 answers

You can do this most easily with the /e 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); 

Look at the action .

You can customize the pattern that matches the replacement strings (which is {\w+} : one or more alphanumeric characters or underscores between curly braces). Including it in a function is trivial.

+11
source

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; 
+2
source

Maybe you should take a look at preg_replace .

0
source
 $string = "Hello my name is {$data["name"]} and I'm {$data["age"]} years old."; 

will do exactly what you want. If this doesn't suit you, try something like a regex loop, like

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

Not tested, you can consult the documentation.

0
source

You can try vsprintf , it has a 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" 
0
source

I have 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. 

Another advantage of this is that you can define different types of placeholder prefix. Here's how Drupal does it; @ indicates a string that should be escaped as safe for output to a web page (to avoid injections). The format_string command iterates over your options (e.g. @name and @weather ), and if the first character is @ , then it uses check_plain for the value.

Also answered here: fooobar.com/questions/602371 / ...

0
source

Source: https://habr.com/ru/post/1391752/


All Articles