解析命令行:优化是错误的!
此页面上所有贡献者都忘记了一件事,即您可以用单引号或双引号将 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)
?>