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

3
  • 2
    From the docs - "An E_DEPRECATED level error is emitted when passing in the "\e" modifier." The function itself is not deprecated. Commented Apr 23, 2014 at 11:39
  • possible duplicate of alternative for function preg_replace e/ modifier Commented Apr 23, 2014 at 11:40
  • @Darragh Thanks, so do i just remove it or replace with? Sorry pretty bad at regular expression. Commented Apr 23, 2014 at 22:44

1 Answer 1

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%}!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.