【问题标题】:How to match all @__('...') on string in php regex?如何在 php 正则表达式中匹配字符串上的所有 @__('...')?
【发布时间】: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


【解决方案1】:

我找到了解决办法,在.+后面加?即可:

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

谢谢巴马尔

使用非贪心量词,以便获得最短匹配,而不是 最长匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    相关资源
    最近更新 更多