簡體   English   中英

在使用PHP的getopt()之后,我怎么知道哪些參數仍然存在?

[英]After using PHP's getopt(), how can I tell what arguments remain?

好的,所以PHP有一個內置的getopt()函數,它返回有關用戶提供的程序選項的信息。 只是,除非我遺漏了什么,否則它完全被淹沒了! 從手冊:

選項的解析將在找到的第一個非選項時結束,后面的任何內容都將被丟棄。

因此getopt()返回一個包含有效和解析選項的數組。 你仍然可以看到通過查看整個原始命令行$argv ,它保持不變,但你怎么知道哪里在命令行getopt()停止解析參數? 如果您想將命令行的其余部分視為其他內容(例如,文件名),則必須知道這一點。

這是一個例子......

假設我想設置一個腳本來接受以下參數:

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 ]開始$argv[ 3 ] ???

從PHP 7.1開始, getopt支持一個可選的by-ref參數, &$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
)

沒有人說你沒有使用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";

我總是這樣做,它的工作原理。 而且我可以做任何我想做的事。

以下內容可用於獲取命令行選項后的任何參數。 它可以在調用PHP的getopt()之前或之后使用,而不會改變結果:

# $options = getopt('cdeh');

$argx = 0;

while (++$argx < $argc && preg_match('/^-/', $argv[$argx])); # (no loop body)

$arguments = array_slice($argv, $argx);

$arguments現在包含任何前導選項后面的任何參數。 或者,如果您不希望參數位於單獨的數組中,則$argx是第一個實際參數的索引: $argv[$argx]

如果在任何前導選項之后沒有參數,則:

  • $arguments是一個空數組[] ,和
  • count($arguments) == 0 ,和
  • $argx == $argc

看一下GetOptionKit來擺脫標志解析。

http://github.com/c9s/GetOptionKit

GetOptionKit可以輕松集成到命令行腳本中。 它支持類型約束,值驗證等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM