barbowza /parse-args
PHP 命令行参数解析实用工具类。提供友好且灵活的 CLI 参数解析。
v1.0.1
2022-08-25 14:10 UTC
Requires
- php: >=8.1
Requires (Dev)
- phpunit/phpunit: ^9.5
- symfony/var-dumper: ^6.1
This package is auto-updated.
Last update: 2024-09-25 18:51:25 UTC
README
PHP 命令行参数解析实用工具类。提供友好且灵活的 CLI 参数解析。
用法
$args = ParseArgs::parseArgs($_SERVER['argv']);
此命令行选项解析器支持三种类型选项的任意组合[单个字符选项(-a -b 或 -ab 或 -c -d=dog 或 -cd dog),长选项(--foo 或 --bar=baz 或 --bar baz)和参数(arg1 arg2)],并返回一个简单数组。
[pfisher ~]$ php test.php --foo --bar=baz --spam eggs
["foo"] => true
["bar"] => "baz"
["spam"] => "eggs"
[pfisher ~]$ php test.php -abc foo
["a"] => true
["b"] => true
["c"] => "foo"
[pfisher ~]$ php test.php arg1 arg2 arg3
[0] => "arg1"
[1] => "arg2"
[2] => "arg3"
[pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --also-funny=spam=eggs \
> 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
[0] => "plain-arg"
["foo"] => true
["bar"] => "baz"
["funny"] => "spam=eggs"
["also-funny"]=> "spam=eggs"
[1] => "plain arg 2"
["a"] => true
["b"] => true
["c"] => true
["k"] => "value"
[2] => "plain arg 3"
["s"] => "overwrite"
不支持:-cd=dog。
@author Patrick Fisher patrick@pwfisher.com
@since 2009年8月21日
@see
- https://php.ac.cn/manual/en/features.commandline.php
- comment #81042 function arguments($argv) by technorati at gmail dot com, 2008年2月12日
- comment #78651 function getArgs($args) by B Crawford, 2007年10月22日
注意:parseArgs.php 包含相同代码的“压缩”版本,供您复制粘贴使用。适用于需要良好界面的小脚本。