I’m trying to extract all the queries from a PHP file. I use PHP reflection to retrieve the content of a method.
When I use reflection the string looks a bit like this:
DB::statement('n
ALTER TABLE `activity` n
ADD `deleted_at` TIMESTAMP NULLn
');n
DB::statement('n
ALTER TABLE `activity_recurrence` n
ADD `deleted_at` TIMESTAMP NULLn
');n
I’m trying to capture anything inside the statement()
function. I’ve been trying a lot of different regex options but I’m unable to crack the case.
I’m now using this regex: ()(([^)]*))
. It grabs anything between parenthesis but does not check if it has a statement
suffix. I’ve been playing around with this answer, but I don’t get it working.
Thanks in advance!
2
Answers
So arkascha set me in the right direction. Below is a vanilla PHP solution.
In my case I will be using it like this:
If you want to anything inside the statement function, you might use a recursive pattern with 2 capture groups.
Then you can take the group 2 value.
Explanation
bDB::statement
(
Capture group 1(
Match(
(
Capture group 2(?>[^()]++|(?1))*
Atomic group, match either 1 or more chars other than parenthesis, or recurse the first subpattern using(?1)
)
Close group 2)
Match)
)
Close group 1See a regex101 demo.
Note that can still be a brittle solution as you want to match sql statements.