Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created December 18, 2015 15:57
Show Gist options
  • Save kgaughan/1cad09fa79e663e02560 to your computer and use it in GitHub Desktop.
Save kgaughan/1cad09fa79e663e02560 to your computer and use it in GitHub Desktop.
A saner PHP getopt.
<?php
function saner_getopt($opts, $longopts=null, $argv=null) {
if (is_null($argv)) {
$argv = $GLOBALS['argv'];
}
if (is_null($longopts)) {
$longopts = array();
}
$parsed = getopt($opts, $longopts);
// We use this filter to eliminate any options from our argument list.
$filter = array();
foreach ($parsed as $k => $vs) {
if (strlen($k) == 1) {
$flag = '-' . $k;
} else {
$flag = '--' . $k;
if ($vs !== false) {
$flag .= '=';
}
}
if ($vs === false) {
$filter[$flag] = false;
} elseif (is_array($vs)) {
foreach ($vs as $v) {
$filter[$flag . $v] = false;
}
} else {
$filter[$flag . $vs] = false;
}
}
$args = array();
$copy_args = false;
foreach (array_slice($argv, 1) as $arg) {
if ($arg == '--') {
// Any arguments from this point on should just be copied.
$copy_args = true;
} elseif ($copy_args || !isset($filter[$arg])) {
// Copy the current argument.
$args[] = $arg;
}
}
return array($parsed, $args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment