Last active
August 29, 2015 14:22
-
-
Save scottchiefbaker/ce01255f8848fc040ced to your computer and use it in GitHub Desktop.
PHP $argv processor - add support for single char arguments
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
function args($item = '') { | |
// Throw away the first one (name of script) | |
$args = array_slice($GLOBALS['argv'],1); | |
$ret = array(); | |
for ($i = 0; $i < sizeof($args); $i++) { | |
// If the item starts with "-" it's a key. Ignore items that are single dash words (-debug) | |
if (preg_match("/^--?([a-zA-Z_]\w*)/",$args[$i],$m) && !preg_match("/^-\w\w/",$args[$i])) { | |
$key = $m[1]; | |
// If the next item does not start with "--" it's the value for this item | |
if (!empty($args[$i + 1]) && !preg_match('/^--?\D/',$args[$i + 1])) { | |
$ret[$key] = $args[$i + 1]; | |
// Bareword like --verbose with no options | |
} else { | |
empty($ret[$key]) ? $ret[$key] = 1 : $ret[$key]++; | |
} | |
// Handle strings of chars like -cvpzf 'test.txt' | |
} elseif (preg_match("/^-(\w\w+)/",$args[$i],$m)) { | |
$chars = str_split($m[1]); | |
foreach ($chars as $c) { | |
$ret[$c] = true; | |
} | |
// If the next arg is not a --option or -f it's value for the last char | |
if (!empty($args[$i + 1]) && !preg_match('/^--?\D/',$args[$i + 1])) { | |
$ret[$c] = $args[$i + 1]; | |
} | |
} | |
} | |
// If we're looking for a certain item | |
if (!empty($item)) { return $ret[$item]; } | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment