开发者

Regex for a Function Call with Multiple Optional Parameters

I'm looking for a regex that will scan a document to match a function call, and return the value of the first parameter (a string literal) only.

The function call could look like any of the following:

MyFunction("MyStringArg");

MyFunction("MyStringArg", true);

MyFunction("MyStringArg", true, true);

I'm currently using:

$pattern = '/Use\s*\(\s*"(.*?)\"\s*\)\s*;/';

This pattern will only match the first form, however.

Thanks in advance f开发者_开发知识库or your help!

Update I was able to solve my problem with:

$pattern = '/Use\s*\(\s*"(.*?)\"/';

Thanks Justin!

~Scott


If you only care about the value of the first parameter, you can just chop off the end of the regex:

$pattern = '/Use\s*\(\s*"(.*?)\"/';

However, you should understand that this (or any pure-regex solution for this problem) will not be perfect, and there will be some possible cases it handles incorrectly. In this case, you'll get false positives, and escaped quotes (\") will break it.

You can ignore escaped quotes by complicating it a bit:

$pattern = '/Use\s*\(\s*"(.*?)(?!<(?:\\\\)*\\)\"/';

This ignores " characters inside the quoted string if they have an odd number of backslashes in front of them.

However, the false-postives issue can't be helped without introducing false-negatives, and vice versa. This is because PHP is an irregular language, so it can't be parsed with "pure" regex, and even modern regex engines that allow recursion are going to need some pretty complex code to do a really thorough job at this.

All I'm saying is, if you're planning a one-off job to quickly scrape through some PHP you wrote yourself, regex is probably fine. If you're looking for something robust and open-ended that will do this on arbitrary PHP code, you need some kind of reflection or PHP parser.


This might be slightly simpler, though will only work if you have double quotes and not single quotes:

$pattern = /Use\s*[^\"]*\"([^\"]*)\"/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜