简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM