PHP 명령줄 매개변수 구문 분석 도구 클래스의 샘플 코드

黄舟
풀어 주다: 2023-03-06 16:18:02
원래의
1551명이 탐색했습니다.

PHP 명령줄 매개변수 구문 분석 도구 클래스의 샘플 코드

<?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(&#39;Not a valid callback function [%s].&#39;, $callback));
		}
		if(isset(self::$optsArr[$opt])) {
			// call user function
			call_user_func($callback, self::$optsArr[$opt]);
		} else {
			throw new Exception(sprintf(&#39;Unknown option [%s].&#39;, $opt));
		}
	}
	
	/**
	 * 是否是 -s 形式的短选项
	 */
	public static function isShortOptions($opt) {
		if(preg_match(&#39;/^\-([a-zA-Z])$/&#39;, $opt, $matchs)) {
			return $matchs[1];
		}
		return false;
	}
	
	/**
	 * 是否是 -hlocalhost 形式的短选项
	 */
	public static function isShortOptionsWithValue($opt) {
		if(preg_match(&#39;/^\-([a-zA-Z])([\S]+)$/&#39;, $opt, $matchs)) {
			self::$shortOptVal = $matchs[2];
			return $matchs[1];
		}
		return false;
	}
	
	/**
	 * 是否是 --help 形式的长选项
	 */
	public static function isLongOptions($opt) {
		if(preg_match(&#39;/^\-\-([a-zA-Z0-9\-_]{2,})$/&#39;, $opt, $matchs)) {
			return $matchs[1];
		}
		return false;
	}
	
	/**
	 * 是否是 --options=opt_value 形式的长选项
	 */
	public static function isLongOptionsWithValue($opt) {
		if(preg_match(&#39;/^\-\-([a-zA-Z0-9\-_]{2,})(?:\=(.*?))$/&#39;, $opt, $matchs)) {
			$tmpV = trim($matchs[2], &#39;"&#39;);
			self::$shortOptVal = empty($tmpV) ? true : $tmpV;
			return $matchs[1];
		}
		return false;
	}
	
	/**
	 * 是否是命令行参数
	 */
	public static function isArg($value) {
		return ! preg_match(&#39;/^\-/&#39;, $value);
	}
	
	/**
	 * 解析命令行参数
	 */
	public static function parseArgs() {
		global $argv;
		
		if(self::$isParse) {
			return ;
		}
		
		// index start from 1.
		$index = 1;
		$length = count($argv);
		$retArgs = array(&#39;opts&#39;=>array(), &#39;args&#39;=>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[&#39;opts&#39;][$key] = $argv[$index];
				} else {
					$retArgs[&#39;opts&#39;][$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[&#39;opts&#39;][$key] = self::$shortOptVal;
			} // command args
			else if( self::isArg($curVal) ) {
				$retArgs[&#39;args&#39;][] = $curVal;
			}
			// incr index
			$index++;
		}
		
		self::$optsArr = $retArgs[&#39;opts&#39;];
		self::$argsArr = $retArgs[&#39;args&#39;];
		self::$isParse = true;
		
		return $retArgs;
	}
}
로그인 후 복사

사용 방법은 다음과 같습니다.

<?php
include &#39;CommandLine.php&#39;;

$args = CommandLine::parseArgs();
print_r($args);

// or
$cmd = new CommandLine();
$cmd->option(&#39;h&#39;, function ($val){
	// 处理选项 h 
	// $val 选项值
	// ...
	echo &#39;Option h handler.&#39;;
});
로그인 후 복사

명령줄 테스트:


위 내용은 PHP 명령줄 매개변수 구문 분석 도구 클래스의 샘플 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!