Here's a utility function to parse command line arguments.
* CommandLine class
*
* @package Framework
*/
/**
* Command Line Interface (CLI) utility class.
*
* @author Patrick Fisher
* @since August 21, 2009
* @package Framework
* @subpackage Env
*/classCommandLine{/**
* PARSE ARGUMENTS
*
* [pfisher ~]$ echo "<?php
* > include('CommandLine.php');
* > \$args = CommandLine::parseArgs(\$_SERVER['argv']);
* > echo "\n", '\$out = '; var_dump(\$args); echo "\n";
* > ?>" > test.php
*
* [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
* > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
*
* $out = array(12) {
* [0] => string(9) "plain-arg"
* ["foo"] => bool(true)
* ["bar"] => string(3) "baz"
* ["funny"] => string(9) "spam=eggs"
* ["alsofunny"] => string(9) "spam=eggs"
* [1] => string(11) "plain arg 2"
* ["a"] => bool(true)
* ["b"] => bool(true)
* ["c"] => bool(true)
* ["k"] => string(5) "value"
* [2] => string(11) "plain arg 3"
* ["s"] => string(9) "overwrite"
* }
*
* @author Patrick Fisher
* @since August 21, 2009
* @see http://www.php.net/manual/en/features.commandline.php
* #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
* #78651 function getArgs($args) by B Crawford, 22-Oct-2007
* @usage $args = CommandLine::parseArgs($_SERVER['argv']);
*/public static functionparseArgs($argv){array_shift($argv);$out= array();
foreach ($argvas$arg){// --foo --bar=bazif (substr($arg,0,2) =='--'){$eqPos=strpos($arg,'=');// --fooif ($eqPos===false){$key=substr($arg,2);$value= isset($out[$key]) ?$out[$key] :true;$out[$key] =$value;
}// --bar=bazelse {$key=substr($arg,2,$eqPos-2);$value=substr($arg,$eqPos+1);$out[$key] =$value;
}
}// -k=value -abcelse if (substr($arg,0,1) =='-'){// -k=valueif (substr($arg,2,1) =='='){$key=substr($arg,1,1);$value=substr($arg,3);$out[$key] =$value;
}// -abcelse {$chars=str_split(substr($arg,1));
foreach ($charsas$char){$key=$char;$value= isset($out[$key]) ?$out[$key] :true;$out[$key] =$value;
}
}
}// plain-argelse {$value=$arg;$out[] =$value;
}
}
return$out;
}
}?>