Php 解析字符串以提取函数名和参数,以便与'call\u user\u func()一起使用`
如何执行Php 解析字符串以提取函数名和参数,以便与'call\u user\u func()一起使用`,php,Php,如何执行事务(123)功能 通过API的响应是:transaction(123) 我将其存储在$response变量中 <?php function transaction($orderid) { return $orderid; } //api response $response = "transaction(123)"; try { $orderid = call_user_func($response); echo $orderid; } catch (Exc
事务(123)
功能
通过API的响应是:transaction(123)
我将其存储在$response
变量中
<?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";
}
?>
通过以下方式调用用户函数:
$orderid = call_user_func('transaction', 123);
此外,请根据用例中应使用两个参数调用的参数来查看
$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]);
显然,如果这些值来自不受信任的源,则需要非常小心。这样做的错误方法是使用
eval()
函数。在您的用例中,这是非常糟糕的,因为API可能会返回您不想执行的内容
这样做的好方法是解析字符串,验证其内容,并相应地映射调用及其参数
可以使用正则表达式分析返回字符串:
preg_match("/^(.+?)\((.*?)\)$/", $answer, $match);
var_dump($match[1]); // method
var_dump(explode(',', $match[2])); // arguments
您必须对上述内容进行清理/验证。我知道这一点,但我需要获得123的值或参数才能执行此操作。@user622378:查看您的代码,似乎您实际上不知道这一点。好的。那么为什么要投反对票呢?这是一个完全合理的答案.我如何提取它。。示例请将$matches[1]和$matches[2]作为数组返回。@user622378已更新。我不是想用
preg\u match\u all()
,而是想用preg\u match()
。