Bill
Bill

Reputation: 19268

PHP convert preg_replace to preg_replace_callback

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

Upvotes: 0

Views: 380

Answers (1)

jonnu
jonnu

Reputation: 728

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%}!

Upvotes: 1

Related Questions