[Pmwiki-users] arg-parsing for markup()

Knut Alboldt pmwiki
Wed Nov 10 14:23:33 CST 2004


well I don't know if this of any interest but I thought I post it  anyway

When implementing own markups I have to process a lot parameters passed  like:
(:markup arg1 +arg2 -arg3 arg4=string :)

so I wrote a short function to to this. The original is from PITS.php so I 
didn't write but modified that function, to be honest :-). defaults for the 
args can be defined easily. Comments are included in the code.

I first wanted to create a cookbook but it's not a complete function to 
expand pmwiki but more a development-recipe so I didn't know where to put 
it. If wanted I can create a cookbook-entry.

Knut


#--------
function GetDirectiveArgs($args,$opt=array())
{
   # adopted from PITS.php
   # parse passed string into single arguments
   # arg-format: results in:
   # "arg1"               $arg['arg1'] = 1
   # "+arg2"              $arg['arg2'] = 1
   # "-arg3"              $arg['arg3'] = 0
   # "arg4=string"        $arg['arg4'] = 'string'
   # "arg5=string_string" $arg['arg5'] = 'string string'
   #
   # default values can be passed in the second parameter (as an array)
   # sample call see below

   $terms = preg_split('/((?<!\\S)[-+]?[\'"].*?[\'"](?!\\S)|\\S+)/',
     $args,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

   # @DEBUG(print_r($terms,true),1);

   foreach($terms as $t) {
     if (trim($t)=='') continue;
     if (preg_match('/([^\'":=]*)[:=]([\'"]?)(.*?)\\2$/',$t,$match))
       $opt[$match[1]] = str_replace("_"," ",$match[3]);
     else
     {
       if (substr($t,0,1)=='-')
         { $opt[substr($t,1)] = 0; }
       elseif (substr($t,0,1)=='+')
         { $opt[substr($t,1)] = 1; }
       else
         { $opt[$t] = 1;  }
     }
   }

   return $opt;
}

# for testing use:
#  (:testgetarg arg1 arg2=value2 arg3=value_with_virtual_blanks +arg4 -arg5 :)

Markup('testgetarg','testgetarg','/\\(:testgetarg\\s*(.*?)\\s*:\\)/e','TestGetArg("$1")');

function TestgetArg($args)
{
   $opt['default'] = 'DEFAULT';
   $opt['arg1']    = 'DEFAULT ARG1';
   $arglist = GetDirectiveArgs($args,$opt);
   echo "<pre>".print_r($arglist,true)."</pre>";
}
#--------- 




More information about the pmwiki-users mailing list