Как я могу разобрать аргументы командной строки в PHP?

Я вызываю PHP скрипт из командной строки $ php my_script.php --num1=124 --first_name=don

Как я могу получить доступ к любой пары ключ-значение, переданные в этот скрипт? Ключи могут быть произвольными, поэтому с помощью getopt() с определенными значениями не будет работать.

Вот то, к чему я хочу получить доступ в моем сценарии:

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

Если я использую var_dump($argv)Я получаю этот вывод:

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

Должен ли я просто посмотреть

3

Решение

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

Другие решения

Я использовал что-то вроде этого из PHP командная строка

и это будет производить что-то вроде

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;
}
1