php getOpts for variables

Since I started developing the phpcli and making something useful out of it, I needed a getOpts-like function for php to parse the command arguments passed in the browser.

The default getopts() function from php himself won’t do good because it’s only for php-cli (using a real cli and executing php files like normal executable files). So I needed a similar function like that . Googled for months, nothing..

I finally got the guts to start with the function preg_match(), quickly learned some regex language (actually, it isn’t that hard) and after one quick hour I got myself a new function getopt_array().

What it does

it does what it says it does, by meaning, it convert an list of words -separated by a space- and search for arguments starting with “-” and creates an array with all the arguments and his values.

the code

function getopt_array($args){
$opts = array();
preg_match_all('#"([^"]+)"#', $args, $matches);
foreach ($matches[0] as $key => $value){
	$_value = str_replace(" ","_MySpaceFace_",$value);
	$strings[$key][] = $value;
	$strings[$key][] = $_value;
foreach ($strings as $value){
 $args = str_replace($value[0],$value[1],$args);
$args = preg_split("/\s+/",$args);
	while (list($key, $val) = each($args)) {

		if (preg_match("/^-(.*)=(.*)/",$val)){
			$opt = explode ("=",$val);
			$opts[$opt[0]] = $opt[1];
		elseif (preg_match("/^-/",$val)){
			$next_arg = $args[$key+1];
			if (!preg_match("/^-/",$next_arg)){
				if (preg_match("/^\"/",$next_arg)){
				$next_arg = str_replace("_MySpaceFace_"," ",str_replace("\"","",$next_arg));
				$opts[$val] = $next_arg;
			} else {
				$opts[$val] = true;
return $opts;

feel free to play around or use the code, but put a link somewhere to this site :)

ps: quoted values are not supported. Couldn’t figure that out. drop a comment if you got the sollution ;)

UPDATE: code updated. Got the quoted values working with help from . thanx guy’s!


subutux wrote 34 posts

Post navigation

Leave a Reply