English 中文(简体)
pattern matching an array, not their elements per se
原标题:

I m looking for a way of pattern matching the "geometry" of an array, the order in which the elements appear, not the contents of each element directly.

Let me outline what I mean by some examples. Given the target array:

array( T_STRING , T_VARIABLE , ASSIGN , T_STRING , LPAREN , T_VARIABLE , COMMA , T_VARIABLE , RPAREN );
//as a matter of fact, these would be the tokens for the PHP code "foo $var = Foo($arg1,$arg2) 

Then the following "pattern" would match, returning the 0-based indexes of the matches, as well as the indexes of the groupings, just like preg_match_all() would do for strings:

array( T_STRING ,  ? ,  ( ,  T_VARIABLE ,  ASSIGN   ) ,  ? ,
     T_STRING ,  LPAREN ,  ( ,  T_VARIABLE ,  COMMA ,  ? ,  ) ,  ? ,  RPAREN );

This is only a simplified PoC, the way I intend to use it is much more complicated, and I don t want to use the full parser generator from PEAR (the lemon port to PHP), which would be overkill.

Are you aware of a function (possibly not an internal PHP function) or project which does just that?

Thank you.

最佳回答

When ever I hear "pattern matching" I think "regex".

Push that array to a string and match against the pattern you re looking for using regex. You may be able to a symbol replacement to make the regex small and manageable:

Your array above could be reduced to a string like this:

$arrayPattern =  SVASL_PVCVR_P 

Now you can use RegEx to match against it.

if (preg_match( /VA/ , $arrayPattern)) 
  print "You ve got a Variable followed by an Assign!";

Just a thought....

问题回答

If you are you looking for Code Analysis, then these slides of Sebastian Bergmann might be of use to you. Starting with slide 17 is examples for analysis by tokens.





相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

How to get instance from string in C#?

Is it possible to get the property of a class from string and then set a value? Example: string s = "label1.text"; string value = "new value"; label1.text = value; <--and some code that makes ...

XML DOM parsing br tag

I need to parse a xml string to obtain the xml DOM, the problem I m facing is with the self closing html tag like <br /> giving me the error of Tag mismatch expected </br>. I m aware this ...

Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

Locating specific string and capturing data following it

I built a site a long time ago and now I want to place the data into a database without copying and pasting the 400+ pages that it has grown to so that I can make the site database driven. My site ...

热门标签