Need regex for trivial object parsing

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Need regex for trivial object parsing

Post 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 :)
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post 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 :(
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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);
Post Reply