[英]Parsing through command line arguments/argv
So I have to make a parser that parses through command line arguments that are passed into it. 所以我必须创建一个解析器来解析传递给它的命令行参数。 Below is the code that I have so far.
下面是我到目前为止的代码。
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;
}
This is the function in which I parse the command line arguments. 这是我解析命令行参数的函数。 My problem is that when I enter "php testArgs.php -v -T 4 -l val1,val2,val3 --names=Austin,Duncan,Eddie --type=gold" it prints it out as
我的问题是,当我输入“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
)
The second and last two array slots are perfectly correct, however the rest SHOULD be printed out as follows. 第二个和最后两个阵列插槽是完全正确的,但其余部分应该按如下方式打印出来。
[T] => 4
[l] => val1,val2,val3
Also the first array key value pair, [0] => testArgs.php should no be shown. 此外,不应显示第一个数组键值对[0] => testArgs.php。
Your second and third else if
blocks should be simpler. 你的第二个和第三个
else if
块应该更简单。 Try something like this: 尝试这样的事情:
<?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 = "";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.