divix
divix

Reputation: 1374

PHP Regex the nested section based on defined parent

I am trying to match a nested content section of the config based on the alias.

I have the base prototype working for matching single aliases over here: https://regex101.com/r/1vwKsx/1 (section correctly matched to: 'template_path_stack' =>)

HOWEVER, I want to select a section (which is re-used in the file) based on the section container. In the link above, I need to only match the section which is inside: controllers => factories.

The problem is that the regex matches both (the correct one and the one from the outside). https://regex101.com/r/IrV0SN/1

Current regex:

('factories' => )(\[((?>[^\[\]]++|(?2))*)\])

Upvotes: 1

Views: 30

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

You may add an obligatory prefix to the regex and discard the matched text using \K operator:

'controllers' => \[\s*\K('factories' => )(\[((?>[^][]++|(?2))*)])

See the regex demo.

Here,

  • 'controllers' => \[ - a 'controllers' => [ text
  • \s* - zero or more whitespaces
  • \K - discards the text matched so far from the current overall match memory buffer.

Upvotes: 3

Related Questions