Skip to content

Instantly share code, notes, and snippets.

@DenesKellner
Last active February 21, 2023 22:03
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DenesKellner/29a696e4420a4f3e162a935e5cb9ab4f to your computer and use it in GitHub Desktop.
Save DenesKellner/29a696e4420a4f3e162a935e5cb9ab4f to your computer and use it in GitHub Desktop.
Command line argument parser. Very convenient, you can define your switches & parameters as if you were writing the help of your program. Handles string, integer and boolean types, supports numbered arguments (not counting the switches of course), and the same function can be used for declaration and parameter querying. No dependencies.
<?php
function arg($x="",$default=null) {
static $argtext = "";
static $arginfo = [];
/* helper */ $contains = function($h,$n) {return (false!==strpos($h,$n));};
/* helper */ $valuesOf = function($s) {return explode(",",$s);};
// called with a multiline string --> parse arguments
if($contains($x,"\n")) {
// parse multiline text input
$argtext = $x;
$args = $GLOBALS["argv"] ?: [];
$rows = preg_split('/\s*\n\s*/',trim($x));
$data = $valuesOf("char,word,type,help");
foreach($rows as $row) {
list($char,$word,$type,$help) = preg_split('/\s\s+/',$row);
$char = trim($char,"-");
$word = trim($word,"-");
$key = $word ?: $char ?: ""; if($key==="") continue;
$arginfo[$key] = compact($data);
$arginfo[$key]["value"] = null;
}
$nr = 0;
while($args) {
$x = array_shift($args); if($x[0]<>"-") {$arginfo[$nr++]["value"]=$x;continue;}
$x = ltrim($x,"-");
$v = null; if($contains($x,"=")) list($x,$v) = explode("=",$x,2);
$k = "";foreach($arginfo as $k=>$arg) if(($arg["char"]==$x)||($arg["word"]==$x)) break;
$t = $arginfo[$k]["type"];
switch($t) {
case "bool" : $v = true; break;
case "str" : if(is_null($v)) $v = array_shift($args); break;
case "int" : if(is_null($v)) $v = array_shift($args); $v = intval($v); break;
}
$arginfo[$k]["value"] = $v;
}
return $arginfo;
}
if($x==="??") {
$help = preg_replace('/\s(bool|int|str)\s+/'," ",$argtext);
return $help;
}
// called with a question --> read argument value
if($x==="") return $arginfo;
if(isset($arginfo[$x]["value"])) return $arginfo[$x]["value"];
return $default;
}
'Example';{
// define your arguments with a multiline string, like this:
arg('
-q --quiet-mode bool Suppress all error messages
-f --filename str Name of your input document
-m --max-lines int Maximum number of lines to read
');
// then read any value like this:
$maxLines = arg("max-lines",99);
$filename = arg("filename");
$stfuMode = arg("quiet-mode");
// let's see what we got
printf("Value of --max-lines: %s\n",$maxLines);
printf("Value of --quiet-mode: %s\n",$stfuMode);
printf("Value of first unnamed argument: %s\n",arg(1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment