Skip to content

Instantly share code, notes, and snippets.

@lethak
Last active August 29, 2015 14:17
Show Gist options
  • Save lethak/603cd824b922c659cb97 to your computer and use it in GitHub Desktop.
Save lethak/603cd824b922c659cb97 to your computer and use it in GitHub Desktop.
Build proper CLI script argument array
<?php
// Usage:
// php myScript.php --titi tata -foo bar --solo --pincemi=" pincemoi" -baz="dd= bat" -caremba --dry-run --ddd --zzz="qqq"
$params = array();
$argKey = null;
$argValue = null;
foreach ($_SERVER['argv'] as $argv)
{
if($argKey!==null && ( strlen(''.$argv)>2 && substr(''.$argv, 0,2)=="--" || strlen(''.$argv)>1 && substr(''.$argv, 0,1)=="-" ))
$argKey=null;
if($argKey==null && strlen(''.$argv)>2 && substr(''.$argv, 0,2)=="--")
{
$argKey = substr(''.$argv, 2);
$eqPos = strpos($argKey, '=');
if($eqPos!==false)
{
$argKey=substr(''.$argv,2,$eqPos);
$argValue=substr(''.$argv, $eqPos+3);
}
$params[$argKey] = ''.$argValue;
if($argValue!==null) $argKey=null;
$argValue=null;
}
elseif($argKey==null && strlen(''.$argv)>1 && substr(''.$argv, 0,1)=="-")
{
$argKey = substr(''.$argv, 1);
$eqPos = strpos($argKey, '=');
if($eqPos!==false)
{
$argKey=substr(''.$argv,1,$eqPos);
$argValue=substr(''.$argv, $eqPos+2);
}
$params[$argKey] = ''.$argValue;
if($argValue!==null) $argKey=null;
$argValue=null;
}
elseif($argKey!==null && $argValue===null && substr(''.$argv,0,1)!=="-")
{
$argValue = ''.$argv;
$params[$argKey] = $argValue;
$argKey=$argValue=null;
}
}
die('<pre>'.print_r(array($_SERVER['argv'], $params), true).'</pre>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment