解析命令行参数/ argv

时间:2017-02-21 21:52:52

标签: php arrays parsing

所以我必须创建一个解析器来解析传递给它的命令行参数。下面是我到目前为止的代码。

 public function parse($argv = null)
{
    $argv = $this->argsUnparsed;
    $argvs = array();
    array_shift($argvs);
    foreach($argv as $arg)
    {
            // This is supposed to find the -- characters in a string
            if(substr($arg,0,2) == '--')
            {
                    $equals = strpos($arg, '=');
                    // If character in string equals '='  saving anything before it as a key and anything afterward as a value
                    if($equals)
                    {
                            $argvs[substr($arg,2,$equals - 2)] = substr($arg,$equals + 1);
                    }
                    else
                    {
                            $k = substr($arg,2);
                            if(!isset($argvs[$k]))
                            {
                                    $argvs[$k] = true;
                            }

                    }
            }
            else if(substr($arg,0,1) == '-')
            {
                    foreach(str_split(substr($arg,1)) as $k)
                    {
                            if(!isset($argvs[$k]))
                            {
                                    $argvs[$k] = true;
                            }
                            elseif($equals == false)
                            {
                                    $argvs[substr($arg,2,$equals - 2)] = substr($arg,$equals + 1);
                            }
                    }


            }
            else
            {
                    $argvs[] = $arg;
            }
    }
    return $argvs;
}

这是我解析命令行参数的函数。我的问题是,当我输入" php testArgs.php -v -T 4 -l val1,val2,val3 --names = Austin,Duncan,Eddie --type = gold"它打印出来

Array
(
    [0] => testArgs.php
    [v] => 1
    [T] => 1
    [1] => 4
    [l] => 1
    [2] => val1,val2,val3
    [names] => Austin,Duncan,Eddie
    [type] => gold
)

第二个和最后两个数组插槽完全正确,但其余部分应该按如下方式打印出来。

[T] => 4
[l] => val1,val2,val3

第一个数组键值对,[0] =>不应该显示testArgs.php。

1 个答案:

答案 0 :(得分:0)

您的第二个和第三个else if块应该更简单。 尝试这样的事情:

<?php
    ...
    // Check if a key is passed that begins with "-"
    else if(substr($arg,0,1) == '-')
     {
         $k = substr($arg,1);
         if(!isset($argvs[$k]))
         {
                 $argvs[$k] = true;
                 $previous_key = $k;
         }

     }
    // Copy the value being parsed to the previous key
    else if(!is_empty($previous_key))
    {           
        $argvs[$previous_key] = $arg;
    }

    $previous_key = "";