使用RegEx和PHP从命令行解析参数 [英] Parsing parameters from command line with RegEx and PHP
问题描述
我将此作为命令行界面的输入,作为可执行文件的参数:
I have this as an input to my command line interface as parameters to the executable:
-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"
我想要的是使用PHP来获取键值/关联数组中的所有参数,如下所示:
What I want to is to get all of the parameters in a key-value / associative array with PHP like this:
$result = [
'Parameter1' => '1234',
'Parameter2' => '1234',
'param3' => 'Test \"escaped\"',
'param4' => '10',
'param5' => '0',
'param6' => 'TT',
'param7' => 'Seven',
'param8' => 'secret',
'SuperParam9' => '4857',
'SuperParam10' => '123',
];
问题出在以下地方:
- 参数的前缀可以为
-
或--
- 参数的粘合(值分配运算符)可以是
=
符号或空格' '
- 某些参数可能位于引号块内,并且也可能具有不同的分隔符,胶合和前缀,即.分隔符的
?
标记.
- parameter's prefix can be
-
or--
- parameter's glue (value assignment operator) can be either an
=
sign or a whitespace' '
- some parameters may be inside a quote block and can also have different, both separators and glues and prefixes, ie. a
?
mark for the separator.
到目前为止,由于我对RegEx确实很不好,并且仍在学习中,因此:
So far, since I'm really bad with RegEx, and still learning it, is this:
/(-[a-zA-Z]+)/gui
通过它我可以获取以-
...
With which I can get all the parameters starting with an -
...
我可以手动操作explode
整个操作,然后手动对其进行解析,但是有太多的意外事件需要考虑.
I can go to manually explode
the entire thing and parse it manually, but there are way too many contingencies to think about.
推荐答案
您可以尝试使用分支重置功能(?|...|...)
处理值的不同可能格式的方法:>
You can try this that uses the branch reset feature (?|...|...)
to deal with the different possible formats of the values:
$str = '-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"';
$pattern = '~ --?(?<key> [^= ]+ ) [ =]
(?|
" (?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ ) "
|
([^ ?"]*)
)~x';
preg_match_all ($pattern, $str, $matches);
$result = array_combine($matches['key'], $matches['value']);
print_r($result);
在分支重置组中,捕获组在交替的每个分支中具有相同的编号或相同的名称.
In a branch reset group, the capture groups have the same number or the same name in each branch of the alternation.
这意味着(?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ )
(显然)是名为([^ ?"]*)
也是名为capture的
This means that (?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ )
is (obviously) the value named capture, but that ([^ ?"]*)
is also the value named capture.
这篇关于使用RegEx和PHP从命令行解析参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!