解析一个字符串以提取函数名和参数,以便与`call_user_func()`一起使用

时间:2011-05-16 13:28:27

标签: php

如何执行transaction(123)功能?

API的响应是:transaction(123)

我将其存储在$response varible。

<?php

function transaction($orderid) {
  return  $orderid;
}

//api response
$response = "transaction(123)";

try {
  $orderid = call_user_func($response);
  echo  $orderid;
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

?>

4 个答案:

答案 0 :(得分:5)

根据manual page call_user_func(),在您的用例中应该使用两个参数进行调用。

$orderid = call_user_func('transaction', 123);

这意味着您必须从$response变量中单独提取函数和参数:

preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $response, $matches);

将导致$matches数组包含索引1处的函数名称和索引2处的参数。

所以你会这样做:

$orderid = call_user_func($matches[1], $matches[2]);

显然,如果这些值来自不受信任的来源,您需要非常小心。

答案 1 :(得分:3)

执行此操作的不好方法是使用eval()函数。在您的用例中非常不好,因为API很可能会返回您不想执行的内容。

执行此操作的好方法是解析字符串,验证其内容,并相应地映射调用及其参数。

您可以使用正则表达式解析返回字符串:

preg_match("/^(.+?)\((.*?)\)$/", $answer, $match);
var_dump($match[1]); // method
var_dump(explode(',', $match[2])); // arguments

必须清理/验证上述内容。

答案 2 :(得分:1)

以这种方式调用call_user_func:

$orderid = call_user_func('transaction', 123);

此外,请查看http://es.php.net/manual/en/function.call-user-func.php

答案 3 :(得分:-2)

如果您的回复是:

$response = "transaction(123)";

然后简单地

eval($response);

但要注意,您必须首先验证从$ response获得的内容,否则您最终可以使用eval'ing(system('cat /etc/passwd'))等。