note 83414 added to function.getopt

From: Date: Sat, 24 May 2008 20:41:49 +0000
Subject: note 83414 added to function.getopt
Groups: php.notes 
Request: Send a blank email to php-notes+get-139706@lists.php.net to get a copy of this message
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser. <?php /** * Parses $GLOBALS['argv'] for parameters and assigns them to an array. * * Supports: * -e * -e <value> * --long-param * --long-param=<value> * --long-param <value> * <value> * * @param array $noopt List of parameters without values */ function parseParameters($noopt = array()) { $result = array(); $params = $GLOBALS['argv']; // could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly reset($params); while (list($tmp, $p) = each($params)) { if ($p{0} == '-') { $pname = substr($p, 1); $value = true; if ($pname{0} == '-') { // long-opt (--<param>) $pname = substr($pname, 1); if (strpos($p, '=') !== false) { // value specified inline (--<param>=<value>) list($pname, $value) = explode('=', substr($p, 2), 2); } } // check if next parameter is a descriptor or a value $nextparm = current($params); if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params); $result[$pname] = $value; } else { // param doesn't belong to any option $result[] = $p; } } return $result; } ?> A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst and an in-program call parseParameters(array('f')); would yield in a resulting array: Array ( [0] => alfons [a] => 1 [b2] => 1 [c] => 1 [d] => 2 [e] => 3=4 [f] => 1 [1] => alber t [2] => hans [3] => wurst ) As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true". ---- Server IP: 212.124.37.9 Probable Submitter: 85.179.158.63 ---- Manual Page -- http://www.php.net/manual/en/function.getopt.php Edit -- https://master.php.net/note/edit/83414 Del: integrated -- https://master.php.net/note/delete/83414/integrated Del: useless -- https://master.php.net/note/delete/83414/useless Del: bad code -- https://master.php.net/note/delete/83414/bad+code Del: spam -- https://master.php.net/note/delete/83414/spam Del: non-english -- https://master.php.net/note/delete/83414/non-english Del: in docs -- https://master.php.net/note/delete/83414/in+docs Del: other reasons-- https://master.php.net/note/delete/83414 Reject -- https://master.php.net/note/reject/83414 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#139706) next »