Angus
Angus

Reputation: 361

Key Value pairs parsing with optional quotes

I'm trying to parse key value pairs out of a string in PHP. Space separator, quoted/unquoted surrounded by spaces This is my attempt.

preg_match_all("/(\w+)[\s]*=[\s]*(([^'\s]+)|'([^']*)')/", $text, $matches);

The problem with this is that it fills two different arrays with ([^'\s]+) and '([^']*)'

A further improvement would also be allowing for double quotes but any of my attempts has failed.

Upvotes: 4

Views: 1571

Answers (2)

Kamehameha
Kamehameha

Reputation: 5473

Using non-capturing groups can help. It can be done as a small modification in your original regex-

(\w+)[\s]*=[\s]*((?:[^'\s]+)|'(?:[^']*)')
                  ^^           ^^

This makes either value types to be captured in the same group.
Demo Here

EDIT -
As a further modification, if you want to allow double quotes in your values, then try this -

(\w+)[\s]*=[\s]*((?:[^"'\s]+)|'(?:[^']*)'|"(?:[^"]*)")

Demo Here

Upvotes: 6

Amit Joki
Amit Joki

Reputation: 59252

You can use a simpler regex:

(.*)=(.*)

Group 1 contains the key, while Group 2 contains the value.

Upvotes: -2

Related Questions