0

Just wondering how I can convert the following preg_replace() to preg_replace_callback() - I am having difficulty converting to preg_replace_callback() as preg_replace() is been deprecated.

$tableData['query'] = preg_replace('/{%(\S+)%}/e', '$\\1', $tableData['query']);

Replace all $string with $string variable.

Thanks heaps in advance

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
Bill
  • 17,872
  • 19
  • 83
  • 131
  • 2
    From the docs - "An E_DEPRECATED level error is emitted when passing in the "\e" modifier." The function itself is not deprecated. – Darragh Enright Apr 23 '14 at 11:39
  • possible duplicate of [alternative for function preg\_replace e/ modifier](http://stackoverflow.com/questions/12895555/alternative-for-function-preg-replace-e-modifier) – Darragh Enright Apr 23 '14 at 11:40
  • @Darragh Thanks, so do i just remove it or replace with? Sorry pretty bad at regular expression. – Bill Apr 23 '14 at 22:44

1 Answers1

1

You can do it this way. I am assuming you know the dangers of eval, so use this at your own risk.

$locals = get_defined_vars();

$tableData['query'] = preg_replace_callback('/{%(\S+)%}/', function ($match) use ($locals) {
    if (!array_key_exists($match[1], $locals)) {
        // the variable wasn't defined - do your error logic here
        return '';
    }
    return $locals[$match[1]];
}, $tableData['query']);

Additional word of warning - any 'declared' variable is fair game! Nothing to stop me having something like this inside the $tableData['query'] variable:

I am evil and want to see {%super_secret_variable%}!
jonnu
  • 728
  • 4
  • 12