Search code examples
phpevalanonymous-functionpreg-replace-callback

preg_replace_callback with anonymous function


I'm getting this error, but I cannot find out why:

Parse error: syntax error, unexpected $end in C:\wamp\www\test.php(19) : eval()'d code on line 1

Any insight would be appreciated!

$table = '<table><tr><td>${Q*10}</td></tr></table>';

$symbols = array('Q' => 10);

preg_replace_callback('/\${(\w+)([*+-\/])(\d+)}/', function($matches) use ($symbols, $table) {
    return repl($matches, $symbols, $table); 
}, $table);

function repl($tokens, $symbols, $table)
{
    $replace = array_shift($tokens);

    $operand1 = $symbols[$tokens[0]];
    $operator = $tokens[1];
    $operand2 = $tokens[2];

    $val = eval("$operand1 $operator $operand2");
    // Fix: $val = eval("return $operand1 $operator $operand2;");

    $table = str_replace($replace, $val, $table);

    echo $table; // Should be 100
}

// EOF

Solution

  • eval needs to contain a statement or block of statements, not just an expression.

    To actually get the result and assign it you need:

        $val = eval("return $operand1 $operator $operand2;");
    

    As @ggutenberg said, at the very least the semicolon to eschew the syntax error. But the return to do what you intended to do.

    The $matches list will contain the complete string at position [0]. The capture groups start at [1]. You might need to adapt the $tokens assignment in your callback.