note 79286 added to function.getopt

From: Date: Mon, 19 Nov 2007 20:44:42 +0000
Subject: note 79286 added to function.getopt
Groups: php.notes 
Request: Send a blank email to php-notes+get-132410@lists.php.net to get a copy of this message
Although very interesting, koenbollen at gnospamail dot com's update of the argv array fails when option values follow the option with no space : Indeed php MyScript.php5 -t5 and php MyScript.php5 -t 5 with $options="t:" are treated as the same by getopt. This upgraded function should take care of it : File : shift_test.php5 <?php function shift($options_array) { foreach( $options_array as $o => $a ) { // Look for all occurrences of option in argv and remove if found : // ---------------------------------------------------------------- // Look for occurrences of -o (simple option with no value) or -o<val> (no space in between): while($k=array_search("-".$o.$a,$GLOBALS['argv'])) { // If found remove from argv: if($k) unset($GLOBALS['argv'][$k]); } // Look for remaining occurrences of -o <val> (space in between): while($k=array_search("-".$o,$GLOBALS['argv'])) { // If found remove both option and value from argv: if($k) { unset($GLOBALS['argv'][$k]); unset($GLOBALS['argv'][$k+1]); } } } // Reindex : $GLOBALS['argv']=array_merge($GLOBALS['argv']); } print_r($argv); $options_array=getopt('t:h'); shift($options_array); print_r($argv); ?> >php shift_test.php5 -h -t4 param1 param2 will ouptut : Array ( [0] => test.php5 [1] => -h [2] => -t4 [3] => param1 [4] => param2 ) Array ( [0] => test.php5 [1] => param1 [2] => param2 ) >php shift_test.php5 -h -t 4 param1 param2 will ouptut : Array ( [0] => test.php5 [1] => -h [2] => -t [3] => 4 [4] => param1 [5] => param2 ) Array ( [0] => test.php5 [1] => param1 [2] => param2 ) ---- Server IP: 195.221.21.36 Probable Submitter: 194.153.88.6 ---- Manual Page -- http://www.php.net/manual/en/function.getopt.php Edit -- https://master.php.net/note/edit/79286 Del: integrated -- https://master.php.net/note/delete/79286/integrated Del: useless -- https://master.php.net/note/delete/79286/useless Del: bad code -- https://master.php.net/note/delete/79286/bad+code Del: spam -- https://master.php.net/note/delete/79286/spam Del: non-english -- https://master.php.net/note/delete/79286/non-english Del: in docs -- https://master.php.net/note/delete/79286/in+docs Del: other reasons-- https://master.php.net/note/delete/79286 Reject -- https://master.php.net/note/reject/79286 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132410) next »