📜 ⬆️ ⬇️

PREG: conditional masks

Task : there is an input string “single param = true param2 =” string fgfg "", it is necessary to disassemble into parameters.

upd : added capture of singles; Added named captures.
for solving use regular
/(\w+)( (==) )?(?(2)( (\\"\' [?] ?(?(3)(.*?)(?!\x5c )\33( [>) [] +))) / ms
Regular season with named captures:
/ (? P <lvalue> \ w +) (? P <ref> [=])? (? (Ref) (? P <quote> [\ "\ '])? (? (Quote) (? P <multi >. *?) (?! \ x5c) \ 3 | (? P <signle> [^ \ s] +))) / ms

The important point : "([\" \ '])? "We are looking for a string in quotation marks or a word without them. The hitch is that in the above expression we need to either get backref # 2 or not get the expression" (? (2 ) "worked. If the question mark (?) is added to the symbol list" ([\ "\ ']?)", then the back link # 2 will always be captured and the condition "([^ \ s] +)" will never be executed.
')
upd : In addition, I want to say that in PHP the mane is not specified about named captures "(? P <name>)", but they still work (at least in 5.2.4).

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


All Articles