问题描述
有一些 PHP 代码分配给一个变量 ($phpCode),该变量可能包含一个名为 runjustthis() 的函数或/和任何其他 php 代码.
There's some PHP code assigned to one variable ($phpCode) that may contain a function called runjustthis()or/and any other php code.
我正在寻找使用 eval() 仅运行该函数 runjustthis() 的可能性.
I'm looking for a possibility to run just that function runjustthis() with eval().
换句话说,我如何从字符串 $phpCode 中提取(使用正则表达式?)函数 runjustthis(),然后在提取的字符串上调用 eval()?
In other words, how do I extract (with a regex?) the function runjustthis() from the string $phpCode and then call eval() on the extracted string?
伪代码:
$phpCode = "
function runjustthis() {
// some code here...
}
// maybe some more code here...
// Don't execute that:
$something = '123';
somethingElse();
";
$runjustthis = extractFunction("runjustthis", $phpCode);
eval($runjustthis);
推荐答案
您不需要其他任何东西.正如 doc 所说:
You do not need anything else. as the doc says:
代码将在调用 eval() 的代码范围内执行.因此,在 eval() 调用中定义或更改的任何变量在它终止后都将保持可见.
所以你只需要:
<?php
$phpCode = "
function runjustthis() {
return 'Hi';
}
function runjustthis2(){
return 'working?';
}
";
eval($phpCode);
echo runjustthis(). PHP_EOL;
echo runjustthis2();
输出
Hi
working?
但是如果你坚持只获得你想要的功能($phpCode
的一部分),那么你可以这样做:
But if you insists on getting only the function you want(part of $phpCode
), so you can do this:
<?php
$phpCode = "
function runjustthis() {
return 'Hi';
}
function runjustthis2(){
return 'working?';
}
";
function extractFunction($functionName, $code){
$pattern = "/function (?<functionName>$functionName+)\(\)(\s+)?\{[^\}]+\}/m";
preg_match_all($pattern, $code, $matches);
return($matches[0][0]);
}
$runjustthis = extractFunction("runjustthis", $phpCode);
eval($runjustthis);
echo runjustthis();
这只会执行 runjustthis()
函数,而不是在 $phpCode
中编写的其他代码,所以如果我们尝试 runjustthis2()
它会得到这个错误:
This would only execute the runjustthis()
function not other codes which wrote in $phpCode
, so if we try runjustthis2()
it will get this error:
PHP Fatal error: Uncaught Error: Call to undefined function runjustthis2() in your/file/directory/file_name.php
这篇关于PHP eval() - 只有一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!