I need a way to find the end of a method/function with regex in PHP. But i’m wondering if this is even possible.
A function obviously always end with a closing bracket }, but so do if/else, for and while statements and the likes…
Is there any way to find and replace the last bracket of a function with a regular expression?
So i should be able to replace the following:
public function func1 ( $someParam )
{
if ( $someParam ) {
}
else {
}
}
to this:
public function func1 ( $someParam )
{
if ( $someParam ) {
}
else {
}
}]; // <-- note the square bracket and semi-colon
A regular expression is the wrong tool for the job. A regex won’t be able to deal with all the various nesting levels and slew of things you might find inside a function. As mario and Matt Lo suggested in the above comments, you need to use something that parses the text and determines the true structure of the code.
PHP is not a regular language that should be parsed with a regular expression, it’s in BNF and should be parsed as such. (I mean, you could use regex, but you’re setting yourself up for a bad time. You can also name all your variables after kittens if it tickles your fancy.)
The tokenizer mario posted is likely your best bet here, as it moves code into a syntax tree, then you can transform the tree back into code. If you have issues using it be sure to follow up with a new question. I believe the author of that library is still active on this site.