Parsing command arguments in PHP

后端 未结 11 753
萌比男神i
萌比男神i 2020-12-11 01:19

Is there a native \"PHP way\" to parse command arguments from a string? For example, given the following string:

foo \"bar \\\"baz         


        
11条回答
  •  盖世英雄少女心
    2020-12-11 01:48

    I wrote some packages for console interactions:

    Arguments parsing

    There is a package that does the whole arguments parsing thing weew/php-console-arguments

    Example:

    $parser = new ArgumentsParser();
    $args = $parser->parse('command:name arg1 arg2 --flag="custom \"value" -f="1+1=2" -vvv');
    

    $args will be an array:

    ['command:name', 'arg1', 'arg2', '--flag', 'custom "value', '-f', '1+1=2', '-v', '-v', '-v']
    

    Arguments can be grouped:

    $args = $parser->group($args);
    

    $args will become:

    ['arguments' => ['command:name', 'arg1', 'arg2'], 'options' => ['--flag' => 1, '-f' => 1, '-v' => 1], '--flag' => ['custom "value'], '-f' => ['1+1=2'], '-v' => []]
    

    It can do much more, just check the readme.

    Output styling

    You might need a package for output styling weew/php-console-formatter

    Console application

    Packages above can be used standalone or in combination with a fancy console application skeleton weew/php-console

    Note: This solutions are not native but might still be useful to some people.

提交回复
热议问题