Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created October 31, 2012 12:02
Show Gist options
  • Save troelskn/3986688 to your computer and use it in GitHub Desktop.
Save troelskn/3986688 to your computer and use it in GitHub Desktop.
parse_console.php
<?php
function parse_console($argv = null) {
$argv = isset($argv) ? $argv : $_SERVER['argv'];
$basename = array_shift($argv);
$arguments = array();
$options = array();
$switches = array();
$tmp = null;
foreach ($argv as $arg) {
if (preg_match('/^--([^=]+)=(.*)$/', $arg, $reg)) {
// flush
if ($tmp !== null) {
$switches[$tmp] = true;
$tmp = null;
}
// --foo=bar
$options[$reg[1]] = $reg[2];
} elseif (preg_match('/^--([^=]+)$/', $arg, $reg)) {
// flush
if ($tmp !== null) {
$switches[$tmp] = true;
$tmp = null;
}
// --foo
$tmp = $reg[1];
} elseif (preg_match('/^-([^=]+)$/', $arg, $reg)) {
// flush
if ($tmp !== null) {
$switches[$tmp] = true;
$tmp = null;
}
// -f
if (strlen($reg[1]) > 1) {
for ($ii=0; $ii < $reg[1]; ++$ii) {
$switches[$reg[1][$ii]] = true;
}
} else {
$tmp = $reg[1];
}
} elseif ($tmp !== null) {
// option-value
$options[$tmp] = $arg;
$tmp = null;
} else {
$arguments[] = $tmp;
}
}
// flush
if ($tmp !== null) {
$switches[$tmp] = true;
$tmp = null;
}
return array($basename, $arguments, $options, $switches);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment