20.2. Parsing Program Arguments with getopt
Problem
You want to parse program options that may be specified as short or long options, or they may be grouped.
Solution
Use
PEAR’s
Console_Getopt class. Its getopt( ) method can parse both short-style options such as
-a or -b and long-style options
such as --alice or --bob:
$o = new Console_Getopt;
// accepts -a, -b, and -c
$opts = $o->getopt($_SERVER['argv'],'abc');
// accepts --alice and --bob
$opts = $o->getopt($_SERVER['argv'],'',array('alice','bob'));Discussion
To parse short-style options, pass Console_Getopt::getopt( ) the array of command-line arguments and a string
specifying valid options. This example allows -a,
-b, or -c as arguments, alone
or in groups:
$o = new Console_Getopt; $opts = $o->getopt($_SERVER['argv'],'abc');
For the previous option string abc, these are
valid sets of options to pass:
%program.php -a -b -c%program.php -abc%program.php -ab -c
The getopt( ) method returns an array. The first
element in the array is a list of all of the parsed options that were
specified on the command line, along with their values. The second
element is any specified command-line option that
wasn’t in the argument specification passed to
getopt( ). For example, if the previous program is
run as:
% program.php -a -b sneezethen $opts is:
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] =>
)
[1] => Array
(
[0] => b
[1] =>
)
)
[1] => Array
(
[0] => program.php
[1] => sneeze
)
)Put a colon after an option in the specification ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access