0

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!

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • [str\_​replace](https://www.php.net/manual/en/function.str-replace.php)? Or use a template engine – brombeer Jan 31 '23 at 12:24
  • You can try using regex ? https://www.php.net/preg_replace – R. Martin Jan 31 '23 at 12:25
  • @brombeer I wrote custom without built-in functions. – orangecoder Jan 31 '23 at 12:27
  • 1
    _"I wrote custom without built-in functions"_ - it would be pretty nonsensical, to attempt this without _any_ of the existing string functions. Sure, you can write your own thing, that loops over the string content character-by-character, then develop your own detection logic for if you found a match, and then append either original characters or replacement characters to your result string ... – CBroe Jan 31 '23 at 12:31
  • ... but if you really want to go that low-level, then I suppose there must be a reason behind this - like this being a homework assignment, perhaps? Well in that case, it is supposed to test the skills _you_ have acquired, not ours. – CBroe Jan 31 '23 at 12:32
  • @CBroe Not homework – orangecoder Jan 31 '23 at 12:33
  • 1
    Well then give us a _proper_ explanation why you could not use built-in functionality. More than just "I don't want to". – CBroe Jan 31 '23 at 12:34

2 Answers2

2

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

  • That's goog, but some changes I've made:function t($template, $data) { foreach($data as $key => $value) { $template = str_replace("{{{$key}}}", $value, $template); } return $template; } – orangecoder Jan 31 '23 at 12:41
  • please change Your answer to function t($template, $data) { foreach($data as $key => $value) { $template = str_replace("{{{$key}}}", $value, $template); } return $template; } – orangecoder Jan 31 '23 at 12:42
  • Why should i change it? The logic stays the same, even if you change the number of brackets. – Elias Kleppinger Jan 31 '23 at 12:43
  • It is not working when there are two brakcets in the left and right of name variable... – orangecoder Jan 31 '23 at 12:45
  • @Elias In a double quoted string, the inner most curly braces are interpreted by PHP to mean "encapsulate the variable". Effectively, `str_replace()` would be only looking for single-curly-braced placeholders. [Your snippet](https://3v4l.org/fQPVJ). [Corrected snippet](https://3v4l.org/0FTco). – mickmackusa Jan 31 '23 at 21:47
1

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

SelVazi
  • 10,028
  • 2
  • 13
  • 29