note 83843 added to features.commandline

From: Date: Sat, 14 Jun 2008 22:08:58 +0000
Subject: note 83843 added to features.commandline
Groups: php.notes 
Request: Send a blank email to php-notes+get-140443@lists.php.net to get a copy of this message
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 we have reached end of options, //we cast all remaining argvs as arguments if ($endofoptions) { $ret['arguments'][] = $arg; continue; } // Is it a command? (prefixed with --) if ( substr( $arg, 0, 2 ) === '--' ) { // is it the end of options flag? if (!isset ($arg[3])) { $endofoptions = true;; // end of options; continue; } $value = ""; $com = substr( $arg, 2 ); // is it the syntax '--option=argument'? if (strpos($com,'=')) list($com,$value) = split("=",$com,2); // is the option not followed by another option but by arguments 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; } // Is it a flag or a serial of flags? (prefixed with -) if ( substr( $arg, 0, 1 ) === '-' ) { for ($i = 1; isset($arg[$i]) ; $i++) $ret['flags'][] = $arg[$i]; continue; } // finally, it is not option, nor flag, nor argument $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) /* vim: set expandtab tabstop=2 shiftwidth=2: */ ?> ---- Server IP: 195.221.21.36 Probable Submitter: 88.170.168.121 ---- Manual Page -- http://www.php.net/manual/en/features.commandline.php Edit -- https://master.php.net/note/edit/83843 Del: integrated -- https://master.php.net/note/delete/83843/integrated Del: useless -- https://master.php.net/note/delete/83843/useless Del: bad code -- https://master.php.net/note/delete/83843/bad+code Del: spam -- https://master.php.net/note/delete/83843/spam Del: non-english -- https://master.php.net/note/delete/83843/non-english Del: in docs -- https://master.php.net/note/delete/83843/in+docs Del: other reasons-- https://master.php.net/note/delete/83843 Reject -- https://master.php.net/note/reject/83843 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#140443) next »