dongxia1390 2011-05-30 19:22
浏览 23
已采纳

将函数参数列表转换为数组

I'm working on a CMS, and I'm looking for a way to convert a list of function arguments, into an array. For example:

function testfunction($param1, $param2){
$string = "Param1: $param1  Param2: $param2";
return $string;
}

$funcname = 'testfunction';
$params = "'this is, parameter 1', 'this is parameter2'";

//This doesnt work, sends both parameters as the first, dont know why.
echo call_user_func($funcname, $params);


//So I want to split the parameter list:
$paramsarray = preg_split('%Complex Regex%', $params);

//And call thusly:
echo call_user_func_array($funcname, $paramsarray);

I dont know what kind of regex to use here.... I could just explode by ',' but that would explode all commas contained in strings, arrays etc... So I need a regex to do this, I'm ok with regexes, but it seems like there would be a lot of rules in this.

  • 写回答

5条回答 默认 最新

  • duanqi5333 2011-05-30 19:33
    关注

    I guess if you really want to start from a string (instead of an array like others suggested), you could do:

    In PHP 5.3:

    $params = "'this is, parameter 1', 'this is parameter2'";
    $paramsarray = str_getcsv($params, ',', "'");
    

    In PHP 5.1/5.2:

    $fp = fopen('php://temp', 'w+');
    fwrite($fp, $params);
    fseek($fp, 0);
    $paramsarray = fgetcsv($fp, 0, ',', "'");
    
    print_r($paramsarray);
    

    ...and get:

    Array
    (
        [0] => this is, parameter 1
        [1] => this is parameter2
    )
    

    ...then use call_user_func_array.

    If you want to use more complex types (e.g.: arrays or objects), that'll be a real challenge. You'll probably have to use the Tokenizer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大