Catch unexpected options with getopt

I am writing a PHP script and should get some parameters (h, n and v). For me, the best way to get this is to use a function getopt. Also, if an unexpected option is passed, I would like to display a help message. However, the function getoptreturns only expteced options.

Here is my script:

$options = getopt('hnv');

if (!empty($options)) {
    foreach (array_keys($options) as $option) {
        switch ($option) {
            // Run script.
            case 'n':
            case 'v':
                break;
            case 'h':
                // Display help with OK exit code.
                self_usage();
                exit(0);
            default:
                // Display help with ERR exit code.
                self_usage('Too many params');
                exit(1);
        }
    }
}

But if I run my script with an unexpected parameter, for example -p, it starts because the array of options is empty.

php myscript.php -p

If I pass an unexpected option with the expected, it will also start.

php myscript.php -pn
php myscript.php -p -n

I tried to check the count of arguments passed, but this only works if I pass the arguments one by one ( -n -p), and not all in one ( -np).

if ((count($argv) - 1) > count($options)) {
    self_usage();
}

Is there a good way to check for non-excluded options in this case?

!

+4
2

:

// remove script called
unset($argv[0]);
$valid_opts = getopt('hnv');
array_walk($argv, function(&$value, $key) {
    // get rid of not opts
    if(preg_match('/^-.*/', $value)) {
        $value = str_replace('-', '', $value);    
    } else {
        $value = '';
    }

});
$argv = array_filter($argv);
print_r($argv);
print_r($valid_opts);

print_r(array_diff($argv, array_keys($valid_opts)));

array_diff , .

+1

, getopt:

$all = getopt(implode('', array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9'))));
$options = getopt('hnv');
$wrongOptions = array_diff(array_keys($all), array_keys($options));
if (!empty($wrongOptions)) {
    echo("Wrong options: " . implode(', ', $wrongOptions));
    exit(1);
}

, zend.console.getopt, .

0

All Articles