note 94393 deleted from function.getopt by danbrown
| From: | danbrown@php.net | Date: | Mon, 02 Nov 2009 14:45:57 +0000 |
| Subject: | note 94393 deleted from function.getopt by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-162330@lists.php.net to get a copy of this message | ||
Note Submitter: kexianbin at diyism dot com
----
test.php:
function get_opts()
{$result=array();
$params=$GLOBALS['argv'];
array_shift($params);
for ($i=0,$cnt=count($params); $i<$cnt; ++$i)
{$p=$params[$i];
if ($p{0}=='-') //-<param> or --<param>
{$pname=substr($p, 1);
$value=true;;
if ($pname{0}=='-') //--<param>
{if (strpos($p, '=')!==false) //--<param>=<value>
{list($pname, $value)=explode('=', substr($p, 2), 2);
}
else //--<param> <value>
{$pname=substr($pname, 1);
}
}
else
{if (strlen($pname)>1) //-<param><param><param>
{for ($k=0,$cnt1=strlen($pname); $k<$cnt1; ++$k)
{$result[$pname{$k}]=true;
}
continue;
}
}
//check if next parameter is a descriptor or a value
if (isset($params[$i+1]) && $value===true &&
$params[$i+1]{0}!='-')
{$value=$params[$i+1];
++$i;
}
$result[$pname]=$value;
}
else //<value>
{$result[]=$p;
}
}
return $result;
}
var_export(get_opts());
=============================
run: /usr/bin/php test.php alfons -a 1 -bj kkkk -c --d 2 --e=3=4 --f "alber t" hans wurst
get:
array (
0 => 'alfons',
'a' => '1',
'b' => true,
'j' => true,
1 => 'kkkk',
'c' => true,
'd' => '2',
'e' => '3=4',
'f' => 'alber t',
2 => 'hans',
3 => 'wurst',
)