Created
April 28, 2022 11:17
-
-
Save kobus1998/bf75828758cc6fbde7eaa43a7476dd02 to your computer and use it in GitHub Desktop.
parse argv arguments
This file contains 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 | |
(new class { | |
public function __invoke() | |
{ | |
$aArgs = $this->parseArgv($GLOBALS['argv']); | |
var_dump($aArgs); | |
die("\n"); | |
} | |
/** | |
* parse argv | |
* | |
* --option=val | |
* -flag | |
* param | |
* | |
* @param array $aArgs | |
* @return array | |
*/ | |
public function parseArgv($aArgs) | |
{ | |
$iParams = 0; | |
$aResult = [ | |
'options' => [], | |
'flags' => [], | |
'params' => [] | |
]; | |
foreach ($aArgs as $sArg) { | |
if (strpos($sArg, '--') !== false) { | |
list($sKey, $sVal) = explode('=', $sArg); | |
$aResult['options'][trim($sKey, '--')] = $sVal; | |
} elseif (strpos($sArg, '-') !== false) { | |
$aResult['flags'][] = trim($sArg, '-'); | |
} else { | |
$aResult['params'][$iParams] = $sArg; | |
$iParams++; | |
} | |
} | |
return $aResult; | |
} | |
})(); | |
die("\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment