I was looking for an alternative to eval() way to execute a code contained in a string variable, and noticed the preg_replace with the /e modifier.
However, code is evaluated quite weirdly.
For instance, echo() leads to an error in php 5.3.6:
<?php
$code = 'echo( \'Hello, world!\'.PHP_EOL)';
preg_replace('/(.*)/e', $code, '' );
?>
Error message:
Parse error: syntax error, unexpected T_ECHO in /Users/…/test.php(4) : regexp code on line
Fatal error: preg_replace(): Failed evaluating code:
echo( ‘Hello, world!’.PHP_EOL) in /Users/…/test.php on line 4
While print() works, and outputs a Hello, world!:
<?php
$code = 'print( \'Hello, world!\'.PHP_EOL)';
preg_replace('/(.*)/e', $code, '' );
?>
Also, it seems that out of several lines of code, only the first one is executed:
<?php
$t=1;
$code = '$t++;$t++;';
preg_replace('/(.*)/e', $code, '' );
echo $t;
?>
Outputs 2, not 3.
Question: is this code evaluation within PCRE in preg_replace() documented somewhere?
Not found on php.net
The preg_replace
/eeval does not evaluate statements, but just a single expression.Is an expression.
Is not.
And likewise anything that can be followed by a semicolon.
See http://www.php.net/manual/en/language.expressions.php for an rough overview.