Parallel spurious value pairs with optional quotes

I am trying to parse key value pairs from a string in PHP. Space delimiter, quoted / without quotation marks, surrounded by spaces This is my attempt.

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

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

Further improvement will also allow the use of double quotes, but any of my attempts have failed.

+4
source share
2 answers

Using non-capture groups can help. This can be done as a small modification in the original regular expression -

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

This allows you to write value types in one group.
Demo here

EDIT -
, , -

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

+6

:

(.*)=(.*)

1 , 2 - .

0

Source: https://habr.com/ru/post/1533064/


All Articles