Sample code of PHP command line parameter parsing tool class
Sample code of PHP command line parameter parsing tool class
<?php /** * 命令行参数解析工具类 * @author guolinchao */ class CommandLine { // 临时记录短选项的选项值 private static $shortOptVal = null; // options value private static $optsArr = array(); // command args private static $argsArr = array(); // 是否已解析过命令行参数 private static $isParse = false; public function construct() { if(!self::$isParse) { self::parseArgs(); } } /** * 获取选项值 */ public function getOptVal($opt) { if(isset(self::$optsArr[$opt])) { return self::$optsArr[$opt]; } return null; } /** * 获取命令行参数 */ public function getArg($index) { if(isset(self::$argsArr[$index])) { return self::$argsArr[$index]; } return null; } /** * 注册选项对应的回调函数, $callback 应该有一个参数, 用于接收选项值 */ public function option($opt, $callback) { // check if(!is_callable($callback)) { throw new Exception(sprintf('Not a valid callback function [%s].', $callback)); } if(isset(self::$optsArr[$opt])) { // call user function call_user_func($callback, self::$optsArr[$opt]); } else { throw new Exception(sprintf('Unknown option [%s].', $opt)); } } /** * 是否是 -s 形式的短选项 */ public static function isShortOptions($opt) { if(preg_match('/^\-([a-zA-Z])$/', $opt, $matchs)) { return $matchs[1]; } return false; } /** * 是否是 -hlocalhost 形式的短选项 */ public static function isShortOptionsWithValue($opt) { if(preg_match('/^\-([a-zA-Z])([\S]+)$/', $opt, $matchs)) { self::$shortOptVal = $matchs[2]; return $matchs[1]; } return false; } /** * 是否是 --help 形式的长选项 */ public static function isLongOptions($opt) { if(preg_match('/^\-\-([a-zA-Z0-9\-_]{2,})$/', $opt, $matchs)) { return $matchs[1]; } return false; } /** * 是否是 --options=opt_value 形式的长选项 */ public static function isLongOptionsWithValue($opt) { if(preg_match('/^\-\-([a-zA-Z0-9\-_]{2,})(?:\=(.*?))$/', $opt, $matchs)) { $tmpV = trim($matchs[2], '"'); self::$shortOptVal = empty($tmpV) ? true : $tmpV; return $matchs[1]; } return false; } /** * 是否是命令行参数 */ public static function isArg($value) { return ! preg_match('/^\-/', $value); } /** * 解析命令行参数 */ public static function parseArgs() { global $argv; if(self::$isParse) { return ; } // index start from 1. $index = 1; $length = count($argv); $retArgs = array('opts'=>array(), 'args'=>array()); while($index < $length) { // current value $curVal = $argv[$index]; // short options or long options if( ($sp = self::isShortOptions($curVal)) || ($lp = self::isLongOptions($curVal)) ) { // options array key $key = $sp ? $sp : $lp; // go ahead $index++; if( isset($argv[$index]) && self::isArg($argv[$index]) ) { $retArgs['opts'][$key] = $argv[$index]; } else { $retArgs['opts'][$key] = true; // back away $index--; } } // short options with value || long options with value else if( false !== ($key = self::isShortOptionsWithValue($curVal)) || false !== ($key = self::isLongOptionsWithValue($curVal)) ) { $retArgs['opts'][$key] = self::$shortOptVal; } // command args else if( self::isArg($curVal) ) { $retArgs['args'][] = $curVal; } // incr index $index++; } self::$optsArr = $retArgs['opts']; self::$argsArr = $retArgs['args']; self::$isParse = true; return $retArgs; } }
The usage is as follows:
<?php include 'CommandLine.php'; $args = CommandLine::parseArgs(); print_r($args); // or $cmd = new CommandLine(); $cmd->option('h', function ($val){ // 处理选项 h // $val 选项值 // ... echo 'Option h handler.'; });
Command line test:
The above is the detailed content of Sample code of PHP command line parameter parsing tool class. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

Run the child process using the os/exec package, create the command through exec.Command but not execute it immediately; 2. Run the command with .Output() and catch stdout. If the exit code is non-zero, return exec.ExitError; 3. Use .Start() to start the process without blocking, combine with .StdoutPipe() to stream output in real time; 4. Enter data into the process through .StdinPipe(), and after writing, you need to close the pipeline and call .Wait() to wait for the end; 5. Exec.ExitError must be processed to get the exit code and stderr of the failed command to avoid zombie processes.

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle

Useinterfacestodefinecontractsforunrelatedclasses,ensuringtheyimplementspecificmethods;2.Useabstractclassestosharecommonlogicamongrelatedclasseswhileenforcinginheritance;3.Usetraitstoreuseutilitycodeacrossunrelatedclasseswithoutinheritance,promotingD

PHParrayshandledatacollectionsefficientlyusingindexedorassociativestructures;theyarecreatedwitharray()or[],accessedviakeys,modifiedbyassignment,iteratedwithforeach,andmanipulatedusingfunctionslikecount(),in_array(),array_key_exists(),array_push(),arr

breakexitstheloopimmediatelyafterfindingatarget,idealforstoppingatthefirstmatch.2.continueskipsthecurrentiteration,usefulforfilteringitemsliketemporaryfiles.3.gotojumpstoalabeledstatement,acceptableinrarecaseslikecleanuporerrorhandlingbutshouldbeused

Restartyourrouterandcomputertoresolvetemporaryglitches.2.RuntheNetworkTroubleshooterviathesystemtraytoautomaticallyfixcommonissues.3.RenewtheIPaddressusingCommandPromptasadministratorbyrunningipconfig/release,ipconfig/renew,netshwinsockreset,andnetsh
