使用PHP的getopt()之后,我怎么能知道还剩下什么参数呢?

2022-08-30 16:12:26

好的,所以PHP有一个内置的getopt()函数,它返回有关用户提供了哪些程序选项的信息。只是,除非我错过了什么,否则它完全无聊了!从手册中:

选项的解析将在找到第一个非选项时结束,随后的任何内容都将被丢弃。

因此,返回一个仅包含有效和已分析选项的数组。您仍然可以通过查看 来查看整个原始命令行,该命令仍未修改,但是您如何判断命令行中停止解析参数的位置?如果要将命令行的其余部分视为其他内容(例如,文件名),则必须知道这一点。getopt()$argvgetopt()

下面是一个示例...

假设我想设置一个脚本来接受以下参数:

Usage: test [OPTION]... [FILE]...

Options:
  -a  something
  -b  something
  -c  something

然后我可能会这样称呼:getopt()

$args = getopt( 'abc' );

而且,如果我像这样运行脚本:

$ ./test.php -a -bccc file1 file2 file3

我应该期望将以下数组返回给我:

Array
(
    [a] =>
    [b] =>
    [c] => Array
        (
            [0] =>
            [1] =>
            [2] =>
        )
)

所以问题是这样的:我到底应该如何知道这三个未解析的、非选项的争论始于???FILE$argv[ 3 ]


答案 1

从 PHP 7.1 开始,支持一个可选的 by-ref 参数 ,其中包含停止参数解析的索引。这对于将标志与位置参数混合在一起非常有用。例如:getopt&$optind

user@host:~$ php -r '$i = 0; getopt("a:b:", [], $i); print_r(array_slice($argv, $i));' -- -a 1 -b 2 hello1 hello2
Array
(
    [0] => hello1
    [1] => hello2
)

答案 2

没有人说你有使用getopt。您可以按照自己喜欢的任何方式进行操作:

$arg_a = null; // -a=YOUR_OPTION_A_VALUE
$arg_b = null; // -b=YOUR_OPTION_A_VALUE
$arg_c = null; // -c=YOUR_OPTION_A_VALUE

$arg_file = null;  // -file=YOUR_OPTION_FILE_VALUE

foreach ( $argv as $arg )
{
    unset( $matches );

    if ( preg_match( '/^-a=(.*)$/', $arg, $matches ) )
    {
        $arg_a = $matches[1];
    }
    else if ( preg_match( '/^-b=(.*)$/', $arg, $matches ) )
    {
        $arg_b = $matches[1];
    }
    else if ( preg_match( '/^-c=(.*)$/', $arg, $matches ) )
    {
        $arg_c = $matches[1];
    }
    else if ( preg_match( '/^-file=(.*)$/', $arg, $matches ) )
    {
        $arg_file = $matches[1];
    }
    else
    {
        // all the unrecognized stuff
    }
}//foreach

if ( $arg_a === null )    { /* missing a - do sth here */ }
if ( $arg_b === null )    { /* missing b - do sth here */ }
if ( $arg_c === null )    { /* missing c - do sth here */ }
if ( $arg_file === null ) { /* missing file - do sth here */ }

echo "a=[$arg_a]\n";
echo "b=[$arg_b]\n";
echo "c=[$arg_c]\n";
echo "file=[$arg_file]\n";

我总是这样做,它的工作原理。此外,我可以用它做任何我想做的事情。


推荐