解析命令列:最佳化是邪惡的!
此頁面上的所有貢獻者都忘記了一件事,你可以用單引號或雙引號包圍 argv。因此,join 與 preg_match_all 結合在一起始終會破壞這一點 :)
這是一個建議
#!/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)
?>