phparraysregexstringqregularexpression

Regular expression for dotted string with exception


I'm not sure that is it possible to do in one regex, but it doesn't hurt to ask.

I created the expression:

/(?<variable>\w+)((\.(?<method>\w+)\((?<parameter>[^{}%]*)\))|(\.(?<subvariable>\w+)))?/i

which helps me to "convert" dotted strings to arrays or call to methods:

core.settings => $core['settings'] 
core.set(param1, param2) => $core->set('param1', 'param2')

It works very well. But I have no idea how to build a several level expression which will work like this:

  1. string: core.settings
group <variable> = core  
group <subvariable> = settings
  1. string: core.get(param)
group <variable> = core
group <method> = get
group <parameter> = param
  1. string core.settings.time
group <variable> = core
group <subvariable> = settings.time
  1. string core.settings.time.set(param)
group <variable> = core
group <subvariable> = settings.time
group <method> = set
group <parameter> = param

Any ideas? And whether it is generally possible?


Solution

  • You can use

    ^(?<variable>\w+)(?:\.(?<subvariable>\w+(?:\.\w+)*))??(?:\.(?<method>\w+)\((?<parameter>[^{}%]*)\))?$
    

    See the regex demo.

    Details: