模式匹配数组,而不是元素本身 [英] pattern matching an array, not their elements per se
问题描述
我正在寻找一种模式匹配数组几何"的方式,即元素出现的顺序,而不是直接每个元素的内容.
让我通过一些例子来概述我的意思.给定目标数组:
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)'
然后,以下模式"将匹配,返回匹配项从0开始的索引,以及分组的索引,就像preg_match_all()对字符串所做的一样:>
array('T_STRING', '?', '(', 'T_VARIABLE', 'ASSIGN' ')', '?',
'T_STRING', 'LPAREN', '(', 'T_VARIABLE', 'COMMA', '?', ')', '?', 'RPAREN');
这只是一个简化的PoC,我打算使用它的方式要复杂得多,而且我不想使用PEAR的完整解析器生成器(柠檬端口到PHP),这太过分了. /p>
您是否知道执行此操作的函数(可能不是内部PHP函数)或项目?
谢谢.
每当我听到模式匹配"时,我就会认为是正则表达式".
将该数组推入字符串,并使用正则表达式与您要查找的模式匹配.您也许可以替换符号以使正则表达式更小且易于管理:
您上面的数组可以简化为这样的字符串:
$arrayPattern = 'SVASL_PVCVR_P'
现在您可以使用RegEx对其进行匹配.
if (preg_match('/VA/', $arrayPattern))
print "You've got a Variable followed by an Assign!";
只是一个想法....
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....
这篇关于模式匹配数组,而不是元素本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!