如何在PHP中解析命令行参数?

时间:2014-10-23 01:54:44

标签: php command-line

我从命令行$ php my_script.php --num1=124 --first_name=don

调用PHP脚本

如何访问传入此脚本的任何键值对?密钥可以是任意的,因此使用具有特定值的getopt()将不起作用。

以下是我希望在我的脚本中访问的内容:

$my_args = array(
  "num1" => 124,
  "first_name" => "don"
);

如果我使用var_dump($argv),我会收到此输出:

array(
  [0] => "my_script.php",
  [1] => "--num1=5",
  [2] => "--num2=123"
);

我应该看看

2 个答案:

答案 0 :(得分:6)

$my_args = array();
for ($i = 1; $i < count($argv); $i++) {
    if (preg_match('/^--([^=]+)=(.*)/', $argv[$i], $match)) {
        $my_args[$match[1]] = $match[2];
    }
}

答案 1 :(得分:1)

我在PHP commandline

中使用过类似的内容

它会产生类似

的东西
array(4) {
  ["commands"]=>
  array(0) {
  }
  ["options"]=>
  array(2) {
    ["num1"]=>
    string(1) "5"
    ["num2"]=>
    string(3) "123"
  }
  ["flags"]=>
  array(0) {
  }
  ["arguments"]=>
  array(0) {
  }
}

function arguments($args) {
    array_shift($args);
    $endofoptions = false;
    $ret = array(
        'commands' => array(),
        'options' => array(),
        'flags' => array(),
        'arguments' => array(),
    );
    while ($arg = array_shift($args)) {
        // if we have reached end of options,
        //we cast all remaining argvs as arguments
        if ($endofoptions) {
            $ret['arguments'][] = $arg;
            continue;
        }
        // Is it a command? (prefixed with --)
        if (substr($arg, 0, 2) === '--') {
            // is it the end of options flag?
            if (!isset($arg[3])) {
                $endofoptions = true;; // end of options;
                continue;
            }
            $value = "";
            $com = substr($arg, 2);
            // is it the syntax '--option=argument'?
            if (strpos($com, '='))
                list($com, $value) = split("=", $com, 2);
            // is the option not followed by another option but by arguments
            elseif(strpos($args[0], '-') !== 0) {
                while (strpos($args[0], '-') !== 0)
                    $value .= array_shift($args) . ' ';
                $value = rtrim($value, ' ');
            }
            $ret['options'][$com] = !empty($value) ? $value : true;
            continue;
        }
        // Is it a flag or a serial of flags? (prefixed with -)
        if (substr($arg, 0, 1) === '-') {
            for ($i = 1; isset($arg[$i]); $i++)
                $ret['flags'][] = $arg[$i];
            continue;
        }
        // finally, it is not option, nor flag, nor argument
        $ret['commands'][] = $arg;
        continue;
    }
    if (!count($ret['options']) && !count($ret['flags'])) {
        $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
        $ret['commands'] = array();
    }
    return $ret;
}