Question

How can I add a property to a class (or any string in that matter) using regular expressions?

I want to have something like:

<?php

class Foo extends Sth
{
    protected $bar;
}

into:

<?php

class Foo extends Sth
{
    protected $newProperty;
    protected $bar;
}

The entry point for pattern should be keyword class and first {.

What is the best way of doing that? Maybe there is a better way than regular expressions? The classes affected will be of course much more complicated so I don't think that reflections are answer here.

Was it helpful?

Solution

I don't know how complex the other classes can be, but that regex works on the sample you have:

/class[^\r\n]+\R\{(\s*)(?=.*?\})/s

And replacing with:

$0protected $newProperty;$1

regex101 demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top