Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom php function for replacing variable with value in PHP

How to write custom php function for replacing variable with value by passing function parameters?

$template = "Hello, {{name}}!";

$data = [
    'name'=> 'world'
];

echo replace($template, $data);

function replace($template, $data) {

    $name = $data['name'];
    
    return $template;
    
}

echo replace($template, $data); must return "Hello, world!"
Thank You!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way would be to use the built-in str_replace function, like this:

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

return $template;

This loops your data-array and replaces the keys with your values. Another approach would be RegEx

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading