【发布时间】:2022-01-18 02:54:14
【问题描述】:
我有以下字符串,需要匹配字符串中的所有@__('...') 或@__("...")。
$string = <<<EOD
@__('test1') @__('test2 (foo)') @__('test\'3') @__("test4")
@__('test5')
EOD;
预期:
test1
test2 (foo)
test\'3
test4
test5
尝试了一些模式:
这种模式只有在一行只有一个目标字符串时才能匹配:
preg_match_all("/@__\([\'\"](.+)[\'\"]\)/", $string, $matches);
dd($matches);
array:2 [▼
0 => "test1') @__('test2 (foo)') @__('test\'3') @__("test4"
1 => "test5"
]
以下不能匹配包含)的字符串:
preg_match_all("/@__\(['|\"]([^\'][^\)]+)['|\"]\)/", $string, $matches);
dd($matches);
array:4 [▼
0 => "test1"
1 => "test\'3"
2 => "test4"
3 => "test5"
]
提前致谢。
【问题讨论】:
-
使用非贪心量词,这样你就得到了最短的匹配,而不是最长的匹配。
标签: php regex preg-match preg-match-all