Page 1 of 1

Need regex for trivial object parsing

Posted: Thu Dec 08, 2005 4:36 pm
by alex.barylski
Hey all, can someone show me how I would use regex to extract object method invocations using regex?

for example...

Code: Select all

$myobj->func("param1", "param2);
I only need the regex to return to me the two parameters and ONLY if they are strings...so is it possible for regex to do this or will the likely hood of escaped double/single quotes cause regex to choke???

Should I use PHP tokenizer for this problem instead?

Thanks in advance :)

Posted: Thu Dec 08, 2005 4:48 pm
by pickle
Not tested, but this might work:

Code: Select all

$pattern = "/->[\w]*\("(.*)","(.*)"\)/";
preg_match_all($pattern,$code,$matches);

//$matches should now contain all the string arguments
However, this won't catch object methods if variables are passed as parameters, or if they are wrapped in single quotes (not hard to make another pattern to catch those though

Posted: Thu Dec 08, 2005 4:56 pm
by alex.barylski
pickle wrote:Not tested, but this might work:

Code: Select all

$pattern = "/->[\w]*\("(.*)","(.*)"\)/";
preg_match_all($pattern,$code,$matches);

//$matches should now contain all the string arguments
However, this won't catch object methods if variables are passed as parameters, or if they are wrapped in single quotes (not hard to make another pattern to catch those though
Whoa...I really need to brush up on regex...

This is what I have thus far:

Code: Select all

preg_match_all("/func_name\(('|")+('|"), ('|")+('|")\);/"
I'll try yours though, cuz mine didn't work :(

Posted: Thu Dec 08, 2005 5:03 pm
by Chris Corbyn
Pickles wont work... too greedy unfortunately (.*) ... the below regex will work with a two paramater method call as long as both paramaters are double-quoted strings. It has some whitespace flexibility too. You'll need to write a function with a few stages if you want to extract any number of parameters which could be of varying types.

Code: Select all

preg_match('%\$\w+->\w+\(\s*"([^"]*)"\s*,\s*"([^"]*)"\s*\)%', $string, $matches);