note 74363 deleted from features.commandline by bjori
| From: | bjori@php.net | Date: | Sat, 07 Apr 2007 15:32:31 +0000 |
| Subject: | note 74363 deleted from features.commandline by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-125174@lists.php.net to get a copy of this message | ||
Note Submitter: Franz Heinzmann (Frando)
Reason: good for you
----
I wrote the following function to parse all types of command line arguments. It works on both linux
and windows and supports normal options (-r or -xz or -kRla or --verbose), options followed by an
argument (-u root or --user=root), and commands (e.g. $foo.php update all, then update and all would
be commands).
<?php
/**
* Parse console arguments.
*
* @license http://opensource.org/licenses/gpl-license.php
GNU Public License
* @author Franz Heinzmann (Frando)
* @param $args The console argument array (usually $argv)
* @param $arg_opts An array of options that are followed by an argument.
* e.g. shell.php -u admin -v --> $arg_opts = array('u')
* @param $default_options
* @return A associative array, $return['commands'] ia a numeric array of all
* commands, $return['options'] contains the options. The option keys
* are always noted without - or -- and are set to TRUE if they were
* invoked, to the argument if followed by an argument, and if not present
* to their default value or FALSE if no default value was specified.
**/
function parse_args($args = array(), $arg_opts = array(), $default_options = array()) {
$options = $default_options;
$commands = array();
for($i = 1; $i < count($args); $i++) {
$opt = $args[$i];
// is the arg an option (starting with '-') ?
if($opt{0} == "-" && strlen($opt) != 1) {
// do we have multiple options behind one '-'?
if (strlen($opt) > 2 && $opt{1} != "-") {
// each char becomes a key of its own
for($j = 1; $j < strlen($opt); $j++) {
$options[substr($opt, $j, $j)] = true;
}
}
// do we have a longopt (starting with '--')?
elseif ($opt{1} == "-") {
if ($pos = strpos($opt, '=')) {
$options[substr($opt, 2, $pos-2)] = substr($opt, $pos+1);
}
else {
$options[substr($opt, 2)] = true;
}
}
else {
$opt = substr($opt, 1);
// check if the current opt is in $arg_opts (= has to be followed by an argument)
if ((in_array($opt, $arg_opts))) {
if (($args[$i+1] == NULL) || ($args[$i+1] == "") || ($args[$i+1]{0} ==
"-")) {
exit("Invalid input: -$opt needs to be followed by an argument.");
}
$options[$opt] = $args[$i+1];
$i++;
}
else {
$options[$opt] = true;
}
}
}
// if it's not an option, it's a command
else {
$commands[] = $opt;
}
}
return array('options'=>$options, 'commands'=>$commands);
}
?>