Created
December 18, 2015 15:57
-
-
Save kgaughan/1cad09fa79e663e02560 to your computer and use it in GitHub Desktop.
A saner PHP getopt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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