note 75110 added to features.commandline

From: Date: Sat, 12 May 2007 21:55:07 +0000
Subject: note 75110 added to features.commandline
Groups: php.notes 
Request: Send a blank email to php-notes+get-126468@lists.php.net to get a copy of this message
While working with command line scripts it is tedious to handle the arguments in a numerated array. The following code will: If the argument is of the form –NAME=VALUE it will be represented in the array as an element with the key NAME and the value VALUE. I the argument is a flag of the form -NAME it will be represented as a boolean with the name NAME with a value of true in the associative array. <?php function arguments($argv) { $_ARG = array(); foreach ($argv as $arg) { if (ereg('--[a-zA-Z0-9]*=.*',$arg)) { $str = split("=",$arg); $arg = ''; $key = ereg_replace("--",'',$str[0]); for ( $i = 1; $i < count($str); $i++ ) { $arg .= $str[$i]; } $_ARG[$key] = $arg; } elseif(ereg('-[a-zA-Z0-9]',$arg)) { $arg = ereg_replace("-",'',$arg); $_ARG[$arg] = 'true'; } } return $_ARG; } ?> Example: <?php print_r(arguments($argv)); ?> # php5 myscript.php --user=nobody --password=secret -p Array ( [user] => nobody [password] => secret [p] => true ) ---- Server IP: 129.16.214.50 Probable Submitter: 217.10.120.179 ---- Manual Page -- http://www.php.net/manual/en/features.commandline.php Edit -- https://master.php.net/note/edit/75110 Del: integrated -- https://master.php.net/note/delete/75110/integrated Del: useless -- https://master.php.net/note/delete/75110/useless Del: bad code -- https://master.php.net/note/delete/75110/bad+code Del: spam -- https://master.php.net/note/delete/75110/spam Del: non-english -- https://master.php.net/note/delete/75110/non-english Del: in docs -- https://master.php.net/note/delete/75110/in+docs Del: other reasons-- https://master.php.net/note/delete/75110 Reject -- https://master.php.net/note/reject/75110 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#126468) next »