0

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.

Nick
  • 21
  • 2
  • Try `(?:[^\s(]+\(|\G(?!^),\s*)\K(?:"[^"]*"|[^,()]+)(?=[^()]*\);)` to get the separate matches See https://regex101.com/r/R3Lpeu/1 – The fourth bird Oct 19 '19 at 18:35
  • The answer in the question you linked is a bad idea for many reasons (efficiency, naive approach, not strong at all). Instead of trying to find the "good" commas, try to describe the different possible parameters. In general, don't try to split, try to describe. – Casimir et Hippolyte Oct 19 '19 at 18:37

2 Answers2

1

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
}
Zac
  • 1,719
  • 3
  • 27
  • 48
1

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.');
}
Nick
  • 21
  • 2