0

I'm trying to convert a project to php 5.6/7 compatibility. And I'm having issues with this function below.

Original function code:

function parsetemplate($template, $array) {
    return preg_replace('#\{([a-z0-9\-_]*?)\}#Ssie', '( ( isset($array[\'\1\']) ) ? $array[\'\1\'] : \'\' );', $template);
}

My attempt to change from preg_replace() to preg_replace_callback():

function parsetemplate($template, $array) {
    return preg_replace_callback('#\{([a-z0-9\-_]*?)\}#Ssie', '( ( isset($array[\'\1\']) ) ? $array[\'\1\'] : \'\' );', $template);
}

I tried several ways, but none seems to work for me, anyone can help me?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Rui Silva
  • 1
  • 1
  • show the input data which causes issue – RomanPerekhrest Mar 28 '16 at 11:31
  • So: 1) Look into the manual about [`preg_replace_callback()`](http://php.net/manual/en/function.preg-replace-callback.php) 2) Remove the deprecated modifier `e` and replace your replacement with an anonymous function as callback (Second argument). 3) Now your matches will be in an array as the first argument of your function. 4) Since you need `$array` in your callback function, but it would be out of scope you need to pass it by `use()`. So you would end up with something like this: – Rizier123 Mar 28 '16 at 11:46
  • `function parsetemplate($template, $array) { return preg_replace_callback('#\{([a-z0-9\-_]*?)\}#Ssi', function($m)use($array){ return isset($array[$m[1]]) ? $array[$m[1]] : ""; }, $template); }` – Rizier123 Mar 28 '16 at 11:47
  • thanks, works like a charm – Rui Silva Mar 28 '16 at 12:49

0 Answers0