note 93086 added to features.commandline
| From: | patrick at pwfisher dot com | Date: | Sat, 22 Aug 2009 06:59:49 +0000 |
| Subject: | note 93086 added to features.commandline | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-159784@lists.php.net to get a copy of this message | ||
This command line option parser supports any combination of three types of options (switches, flags
and arguments) and returns a simple array.
[pfisher ~]$ php test.php --foo --bar=baz
["foo"] => true
["bar"] => "baz"
[pfisher ~]$ php test.php -abc
["a"] => true
["b"] => true
["c"] => true
[pfisher ~]$ php test.php arg1 arg2 arg3
[0] => "arg1"
[1] => "arg2"
[2] => "arg3"
<?php
function parseArgs($argv){
array_shift($argv);
$out = array();
foreach ($argv as $arg){
if (substr($arg,0,2) == '--'){
$eqPos = strpos($arg,'=');
if ($eqPos === false){
$key = substr($arg,2);
$out[$key] = isset($out[$key]) ? $out[$key] : true;
} else {
$key = substr($arg,2,$eqPos-2);
$out[$key] = substr($arg,$eqPos+1);
}
} else if (substr($arg,0,1) == '-'){
if (substr($arg,2,1) == '='){
$key = substr($arg,1,1);
$out[$key] = substr($arg,3);
} else {
$chars = str_split(substr($arg,1));
foreach ($chars as $char){
$key = $char;
$out[$key] = isset($out[$key]) ? $out[$key] : true;
}
}
} else {
$out[] = $arg;
}
}
return $out;
}
?>
Full version with comments here: http://pwfisher.com/nucleus/index.php?itemid=45
----
Server IP: 69.147.83.197
Probable Submitter: 71.165.91.32
----
Manual Page -- http://www.php.net/manual/en/features.commandline.php
Edit -- https://master.php.net/note/edit/93086
Del: integrated -- https://master.php.net/note/delete/93086/integrated
Del: useless -- https://master.php.net/note/delete/93086/useless
Del: bad code -- https://master.php.net/note/delete/93086/bad+code
Del: spam -- https://master.php.net/note/delete/93086/spam
Del: non-english -- https://master.php.net/note/delete/93086/non-english
Del: in docs -- https://master.php.net/note/delete/93086/in+docs
Del: other reasons-- https://master.php.net/note/delete/93086
Reject -- https://master.php.net/note/reject/93086
Search -- https://master.php.net/manage/user-notes.php