gpt4 book ai didi

PHP eval() - 只有一个函数

转载 作者:行者123 更新时间:2023-12-03 23:39:18 25 4
gpt4 key购买 nike

有一些 PHP 代码分配给一个变量 ($phpCode),它可能包含一个名为 runjustthis() 的函数或/和任何其他 PHP 代码。

我正在寻找使用 eval() 运行函数 runjustthis() 的可能性。

换句话说,我如何从字符串 $phpCode 中提取(使用正则表达式?)函数 runjustthis(),然后对提取的字符串调用 eval()?

伪代码:

$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说:

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

所以你只需要:

<?php
$phpCode = "
function runjustthis() {
return 'Hi';
}

function runjustthis2(){
return 'working?';
}
";

eval($phpCode);
echo runjustthis(). PHP_EOL;
echo runjustthis2();

输出

Hi
working?

但是如果你坚持只得到你想要的函数($phpCode的一部分),那么你可以这样做:

<?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() 它会得到这个错误:

PHP Fatal error:  Uncaught Error: Call to undefined function runjustthis2() in your/file/directory/file_name.php

关于PHP eval() - 只有一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66905929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com