preg_replace code evaluation with /e modifier
Solution 1
The preg_replace /e
eval does not evaluate statements, but just a single expression.
print()
Is an expression.
echo ...;
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.
Solution 2
Your better off creating an anonymous function and calling it using preg_replace_callback
.
Serge
____ _ __ / __/__ _______ _(_) /__ ___ _\ \/ -_) __/ _ `/ / '_/(_-< /___/\__/_/ \_, /_/_/\_\/___/ /___/ Big in Japan
Updated on June 04, 2022Comments
-
Serge almost 2 years
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 4While
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