Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

RegEx to grab all values in quotes

I have this regular expression which does wonders for me:

~--?(?<key>[^= ]+)[ =]
    (?|
        "(?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ )"
      |
        ([^ ?"]*)
    )~x

It allows me to create a PHP key-value / associative array from a string input like this:

-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"

Now, the only problem is that I've got it as an answer for my previous question and I am clueless how to update the regex expression to fit my new needs. RegEx is not my strongest side.

New pattern I'd like to introduce in that expression is (and to keep existing functionality as well):

-parameterX"Value like this, glue is nothing" -paramY"Yes, like this" -paramZ"120983"

I have tried a stupid hack like, intercepting my input string and replacing all quotes with a whitespace added on it's left side, like this:

$input = str_replace('"', ' "', $input);

But this is not what would anyone want...

Upvotes: 1

Views: 62

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627545

You must make sure the key part does not match a double quote, and that [ =] part is optional (since in the new format, there are not spaces between the key and the "..." part.

Use

/--?(?<key>[^= "]+)[ =]?
(?|
    "(?<value> [^\\"]*+ (?s:\\.[^\\"]*)*+ )"
  |
    ([^ ?"]*)
)/x

See this regex demo.

The modified part is (?<key>[^= "]+)[ =]?: [^= "]+ matches one or more chars other than =, space and " (maybe, \w+ will be enough) and [ =]? matches one or zero occurrences of = or a space.

Upvotes: 1

Related Questions