note 125129 added to function.getopt
| From: | taka8aru at gmail dot com | Date: | Sat, 20 Jun 2020 08:40:33 +0000 |
| Subject: | note 125129 added to function.getopt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214780@lists.php.net to get a copy of this message | ||
getopt() simply ignores unnecessary options specified in argv.
Many times, it does not work well to handle errors in command line.
A package PEAR::Console_Getopt can handle this problem, but it requires additonal installation.
GNU getopt(1) does well at shell level.
Following is my extended getopt() can detect unnecessary options:
<?php
function getoptex($sopt, $lopt, &$ind)
{
global $argv, $argc;
$sopts = getopt($sopt, $lopt);
$sopts_cnt = count($sopts); // single-option count based on original sopt
$asopt = $sopt . implode("", range("a", "z")) .
implode("", range("A", "Z")) . implode("",
range("0", "9"));
$asopts = getopt($asopt, $lopt);
$asopts_cnt = count($asopts); // actual single-option count including all single options even if
is not listed as sopt
$lopt_trim = array();
foreach ($lopt as $o) {
$lopt_trim[] = trim($o, ":");
}
$alopts_cnt = 0;
$alopts_flag = true;
for ($i = 1; $i < $argc; $i++) {
if ($argv[$i] === "--") { // end of option
break;
}
if (strpos($argv[$i], "--") === 0) { // actual long-option
$alopts_cnt++;
$o = substr($argv[$i], 2);
if (! in_array($o, $lopt_trim)) { // but it is not listed as lopt
$alopts_flag = false;
} else {
if (in_array(($o . ":"), $lopt)) { // if the option requires value
$i++; // assume next is the value
if ($i >= $argc) { // and the value is missing
$alopts_flag = false;
break;
}
}
}
}
}
//var_dump($sopts, $asopts, $lopts, $alopts_cnt, $alopts_flag);
if ($sopts_cnt != $asopts_cnt || (! $alopts_flag)) {
return false;
} else {
return getopt($sopt, $lopt, $ind);
}
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 220.100.115.55)
----
Manual Page -- http://php.net/manual/en/function.getopt.php
Edit -- https://master.php.net/note/edit/125129
Del: integrated -- https://master.php.net/note/delete/125129/integrated
Del: useless -- https://master.php.net/note/delete/125129/useless
Del: bad code -- https://master.php.net/note/delete/125129/bad+code
Del: spam -- https://master.php.net/note/delete/125129/spam
Del: non-english -- https://master.php.net/note/delete/125129/non-english
Del: in docs -- https://master.php.net/note/delete/125129/in+docs
Del: other reasons-- https://master.php.net/note/delete/125129
Reject -- https://master.php.net/note/reject/125129
Search -- https://master.php.net/manage/user-notes.php