skip to Main Content

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!

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can do it using preg_replace_callback_array to Perform a regular expression search and replace using callbacks.

    This solution is working for multi variables, its parse the entire text, and exchange every indicated variable.

    function replacer($source, $arrayWords) {
        return preg_replace_callback_array(
            [
                '/({{([^{}]+)}})/' => function($matches) use ($arrayWords) {
                    if (isset($arrayWords[$matches[2]])) $returnWord = $arrayWords[$matches[2]];
                    else $returnWord = $matches[2];
                    return $returnWord;
                },
            ], 
            $source);
    }
    

    demo here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search