سؤال

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.

هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top