How to match all @__('...') on string in php regex?

I have the below string and need to match all @__('...') or @__("...") in a string.

        $string = <<<EOD
@__('test1') @__('test2 (foo)') @__('test\'3') @__("test4")
@__('test5')
EOD;

Expected:

test1
test2 (foo)
test\'3
test4
test5

Tried some pattens:

This patten can only match when there is only one target string on a line:

preg_match_all("/@__\([\'\"](.+)[\'\"]\)/", $string, $matches);
    
dd($matches);
    
array:2 [▼
    0 => "test1') @__('test2 (foo)') @__('test\'3') @__("test4"
    1 => "test5"
]

The below one can't match the string that include ):

preg_match_all("/@__\(['|\"]([^\'][^\)]+)['|\"]\)/", $string, $matches);

dd($matches);

array:4 [▼
    0 => "test1"
    1 => "test\'3"
    2 => "test4"
    3 => "test5"
]

Thanks in advance.


Solution 1:

I found a solution, just add ? after .+:

preg_match_all("/@__\([\'\"](.+?)[\'\"]\)/", $string, $matches);

Thanks Barmar

Use a non-greedy quantifier so you get the shortest match, not the longest match.