Command line args parser


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. ?>

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.