Nick
Nick

Reputation: 21

How to parse a string of function parameters with REGEX in PHP

I am trying to handle parameters like Java or PHP natively handle them, using Regex to parse variable numbers (and types) of arguments. For example, a function might be:

util.echo(5, "Hello, world!");

In this instance, I would want to separate 5 as the first argument and "Hello, world!" as the second (without quotes). What I currently do is explode by commas, but that runs into issues if the string parameters include a comma. I don't have much experience with Regex, but I think it has some way of ignoring commas that are within quotes.

The Regex from this question (",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)") seems like it could work, but I'm confused on how to implement it with PHP.

Upvotes: 0

Views: 884

Answers (2)

Nick
Nick

Reputation: 21

Thank you to Zac and The fourth bird! Example solution that works, for future reference:

$parameters = 'util.echo(5, "Hello, world!");';

preg_match_all('/(?:[^\s(]+\(|\G(?!^),\s*)\K(?:"[^"]*"|[^,()]+)(?=[^()]*\);)/', $parameters, $matches);
if($matches){
    var_dump($matches[0]);
} else {
    echo('No matches.');
}

Upvotes: 1

Zac
Zac

Reputation: 2081

To test a regular expression onto a string, you can use the preg_match() function in PHP.

See the manual

// $matches is going to output the matches
preg_match("/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/", $to_be_checked, $matches);
if($matches){
    var_dump($matches);
    // there was a match!
} else {
    // the regular expression did not find any pattern matches
}

if you don't need to access the exact matches, just if there was at least one pattern match, you can simply do this:

if(preg_match("/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/", $to_be_checked)){
    // there was a match!
} else {
    // the regular expression did not find any pattern matches
}

Upvotes: 1

Related Questions