Posted By

maid450 on 06/12/08


Tagged

Shell parser


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

xuanyan
orion
pachanka


Command line args parser


 / Published in: PHP
 

URL: http://es2.php.net/features.commandline

seen in comments in http://es2.php.net/features.commandline

  1. <?php
  2.  
  3. function getArgs($args) {
  4. $out = array();
  5. $last_arg = null;
  6. for($i = 1, $il = sizeof($args); $i < $il; $i++) {
  7. if( (bool)preg_match("/^--(.+)/", $args[$i], $match) ) {
  8. $parts = explode("=", $match[1]);
  9. $key = preg_replace("/[^a-z0-9]+/", "", $parts[0]);
  10. if(isset($parts[1])) {
  11. $out[$key] = $parts[1];
  12. }
  13. else {
  14. $out[$key] = true;
  15. }
  16. $last_arg = $key;
  17. }
  18. else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ) {
  19. for( $j = 0, $jl = strlen($match[1]); $j < $jl; $j++ ) {
  20. $key = $match[1]{$j};
  21. $out[$key] = true;
  22. }
  23. $last_arg = $key;
  24. }
  25. else if($last_arg !== null) {
  26. $out[$last_arg] = $args[$i];
  27. }
  28. }
  29. return $out;
  30. }
  31.  
  32. /*
  33. sample
  34.  
  35. php file.php --foo=bar -abc -AB 'hello world' --baz
  36.  
  37. produces:
  38.  
  39. Array
  40. (
  41.   [foo] => bar
  42.   [a] => true
  43.   [b] => true
  44.   [c] => true
  45.   [A] => true
  46.   [B] => hello world
  47.   [baz] => true
  48. )
  49.  
  50. */
  51.  
  52. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: arturgspb on March 24, 2011

Today I write class for parsing command line arguments in php. It's not spam - I hope it help for any scripts.

http://arturgspb.ru/read/php-parser-argumentov-komandnoj-stroki-command-line-arguments-parser.html

You need to login to post a comment.