note 81176 added to features.commandline
| From: | Anonymous at osu1 dot php dot net | Date: | Sun, 17 Feb 2008 05:29:11 +0000 |
| Subject: | note 81176 added to features.commandline | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-136215@lists.php.net to get a copy of this message | ||
I find regex and manually breaking up the arguments instead of havingon $_SERVER['argv']
to do it more flexiable this way.
cli_test.php asdf asdf --help --dest=/var/ -asd -h --option mew arf moo -z
Array
(
[input] => Array
(
[0] => asdf
[1] => asdf
)
[commands] => Array
(
[help] => 1
[dest] => /var/
[option] => mew arf moo
)
[flags] => Array
(
[0] => asd
[1] => h
[2] => z
)
)
<?php
function arguments ( $args )
{
array_shift( $args );
$args = join( $args, ' ' );
preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match
);
$args = array_shift( $match );
/*
Array
(
[0] => asdf
[1] => asdf
[2] => --help
[3] => --dest=/var/
[4] => -asd
[5] => -h
[6] => --option mew arf moo
[7] => -z
)
*/
$ret = array(
'input' => array(),
'commands' => array(),
'flags' => array()
);
foreach ( $args as $arg ) {
// Is it a command? (prefixed with --)
if ( substr( $arg, 0, 2 ) === '--' ) {
$value = preg_split( '/[= ]/', $arg, 2 );
$com = substr( array_shift($value), 2 );
$value = join($value);
$ret['commands'][$com] = !empty($value) ? $value : true;
continue;
}
// Is it a flag? (prefixed with -)
if ( substr( $arg, 0, 1 ) === '-' ) {
$ret['flags'][] = substr( $arg, 1 );
continue;
}
$ret['input'][] = $arg;
continue;
}
return $ret;
}
print_r( arguments( $argv ) );
?>
----
Server IP: 208.69.120.35
Probable Submitter: 76.171.101.17
----
Manual Page -- http://www.php.net/manual/en/features.commandline.php
Edit -- https://master.php.net/note/edit/81176
Del: integrated -- https://master.php.net/note/delete/81176/integrated
Del: useless -- https://master.php.net/note/delete/81176/useless
Del: bad code -- https://master.php.net/note/delete/81176/bad+code
Del: spam -- https://master.php.net/note/delete/81176/spam
Del: non-english -- https://master.php.net/note/delete/81176/non-english
Del: in docs -- https://master.php.net/note/delete/81176/in+docs
Del: other reasons-- https://master.php.net/note/delete/81176
Reject -- https://master.php.net/note/reject/81176
Search -- https://master.php.net/manage/user-notes.php