简体   繁体   English

如何匹配 php 正则表达式中字符串上的所有 @__('...')?

[英]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.使用非贪婪量词,以便获得最短匹配,而不是最长匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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