List Info

Thread: note 78651 added to features.commandline




note 78651 added to features.commandline
user name
2007-10-21 21:01:26
I have not seen in this thread any code snippets that
support the full *nix style argument parsing. Consider
this:

<?php
print_r(getArgs($_SERVER['argv']));

function getArgs($args) {
 $out = array();
 $last_arg = null;
	for($i = 1, $il = sizeof($args); $i < $il; $i++) {
		if( (bool)preg_match("/^--(.+)/", $args[$i],
$match) ) {
		 $parts = explode("=", $match[1]);
		 $key = preg_replace("/[^a-z0-9]+/",
"", $parts[0]);
			if(isset($parts[1])) {
			 $out[$key] = $parts[1];	
			}
			else {
			 $out[$key] = true;	
			}
		 $last_arg = $key;
		}
		else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/",
$args[$i], $match) ) {
			for( $j = 0, $jl = strlen($match[1]); $j < $jl; $j++ )
{
			 $key = $match[1]{$j};
			 $out[$key] = true;
			}
		 $last_arg = $key;
		}
		else if($last_arg !== null) {
		 $out[$last_arg] = $args[$i];
		}
	}
 return $out;
}

/*
php file.php --foo=bar -abc -AB 'hello world' --baz

produces: 

Array
(
  [foo] => bar
  [a] => true
  [b] => true
  [c] => true
  [A] => true
  [B] => hello world
  [baz] => true
)

*/
?>
----
Server IP: 209.41.74.194
Probable Submitter: 76.81.26.29
----
Manual Page -- http://www.php.net/manual/en/features.commandline.php
Edit        -- https://master
.php.net/note/edit/78651
Del: integrated  -- h
ttps://master.php.net/note/delete/78651/integrated
Del: useless     -- http
s://master.php.net/note/delete/78651/useless
Del: bad code    -- htt
ps://master.php.net/note/delete/78651/bad+code
Del: spam        -- https:/
/master.php.net/note/delete/78651/spam
Del: non-english -- 
https://master.php.net/note/delete/78651/non-english
Del: in docs     -- http
s://master.php.net/note/delete/78651/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78651
Reject      -- https://mast
er.php.net/note/reject/78651
Search      -- https://
master.php.net/manage/user-notes.php

-- 
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php


[1]

about | contact  Other archives ( Real Estate discussion Medical topics )