Parsing command line: optimization is evil!
One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)
Here is a proposal:
#!/usr/bin/php
<?php
print_r(arguments($argv));
function arguments ( $args )
{
array_shift( $args );
$endofoptions = false;
$ret = array
(
'commands' => array(),
'options' => array(),
'flags' => array(),
'arguments' => array(),
);
while ( $arg = array_shift($args) )
{
if ($endofoptions)
{
$ret['arguments'][] = $arg;
continue;
}
if ( substr( $arg, 0, 2 ) === '--' )
{
if (!isset ($arg[3]))
{
$endofoptions = true;; continue;
}
$value = "";
$com = substr( $arg, 2 );
if (strpos($com,'='))
list($com,$value) = split("=",$com,2);
elseif (strpos($args[0],'-') !== 0)
{
while (strpos($args[0],'-') !== 0)
$value .= array_shift($args).' ';
$value = rtrim($value,' ');
}
$ret['options'][$com] = !empty($value) ? $value : true;
continue;
}
if ( substr( $arg, 0, 1 ) === '-' )
{
for ($i = 1; isset($arg[$i]) ; $i++)
$ret['flags'][] = $arg[$i];
continue;
}
$ret['commands'][] = $arg;
continue;
}
if (!count($ret['options']) && !count($ret['flags']))
{
$ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
$ret['commands'] = array();
}
return $ret;
}
exit (0)
?>