PHP argument parser


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

As seen in [maid450](http://snipplr.com/view/6677/)'s profile, added the ability to parse strings, and the ability to parse quoted strings, also the ability to regognize second arguments after "--" flags.


Copy this code and paste it in your HTML
  1. <?php
  2. function parse_args($args) {
  3. $out = array();
  4. $last_arg = null;
  5. if(is_string($args)){
  6. $args = str_replace(array('=', "\'", '\"'), array('= ', '&#39;', '&#34;'), $args);
  7. $args = str_getcsv($args, ' ', '"');
  8. $tmp = array();
  9. foreach($args as $arg){
  10. if(!empty($arg) && $arg != "&#39;" && $arg != "=" && $arg != " "){
  11. $tmp[] = str_replace(array('= ', '&#39;', '&#34;'), array('=', "'", '"'), trim($arg));
  12. }
  13. }
  14. $args = $tmp;
  15. }
  16. for($i = 0, $il = sizeof($args); $i < $il; $i++){
  17. if( (bool)preg_match("/^--(.+)/", $args[$i], $match) ){
  18. $parts = explode("=", $match[1]);
  19. $key = preg_replace("/[^a-zA-Z0-9-]+/", "", $parts[0]);
  20. if(isset($args[$i+1]) && substr($args[$i],0,2) == '--'){
  21. $out[$key] = $args[$i+1];
  22. $i++;
  23. }else if(isset($parts[1])){
  24. $out[$key] = $parts[1];
  25. }else{
  26. $out[$key] = true;
  27. }
  28. $last_arg = $key;
  29. }else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ){
  30. $len = strlen($match[1]);
  31. for( $j = 0, $jl = $len; $j < $jl; $j++ ){
  32. $key = $match[1]{$j};
  33. $val = ($args[$i+1]) ? $args[$i+1]: true;
  34. $out[$key] = ($match[0]{$len} == $match[1]{$j}) ? $val : true;
  35. }
  36. $last_arg = $key;
  37. }else if((bool) preg_match("/^([a-zA-Z0-9-]+)$/", $args[$i], $match) ){
  38. $key = $match[0];
  39. $out[$key] = true;
  40. $last_arg = $key;
  41. }else if($last_arg !== null) {
  42. $out[$last_arg] = $args[$i];
  43. }
  44. }
  45. return $out;
  46. }
  47.  
  48. $str = 'yankee -D "oo\"d l e\'s" -went "2 town 2 buy him-self" -a pony --calledit=" \"macaroonis\' "';
  49. var_dump(parse_args($str));
  50. /* Will output:
  51. array(9) {
  52.   ["yankee"]=>
  53.   bool(true)
  54.   ["D"]=>
  55.   string(10) "oo"d l e's"
  56.   ["w"]=>
  57.   bool(true)
  58.   ["e"]=>
  59.   bool(true)
  60.   ["n"]=>
  61.   bool(true)
  62.   ["t"]=>
  63.   string(21) "2 town 2 buy him-self"
  64.   ["a"]=>
  65.   string(4) "pony"
  66.   ["pony"]=>
  67.   bool(true)
  68.   ["calledit"]=>
  69.   string(12) ""macaroonis'"
  70. }
  71. */

URL: http://snipplr.com/view/6677/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.