PHP正则表达式查找__中包含的字符串(“STRING_TO_EXTRACT”)

时间:2022-09-13 13:18:01

Sorry I really suck at regexp. I need to collect all the string on my application which are enclosed in this example: __("STRING") the string may be enclosed in single quote as well.

对不起,我真的很喜欢regexp。我需要收集我的应用程序中包含在此示例中的所有字符串:__(“STRING”)字符串也可以用单引号括起来。

I tried it with the following code:

我用以下代码尝试了它:

$str = "__('match1') __("match2") do_not_include __('match3')";

preg_match_all("/__\(['\"](.*)['\"]\)/", $str, $matches);
var_dump($matches);

but it is only able to match the entire line string with 1 match. Example result below. Please help me edit the regexp so it should be able to get the 3 matches.

但它只能匹配整个线串与1匹配。以下示例结果。请帮我编辑正则表达式,以便它能够获得3场比赛。

match1') __("match2") do_not_include __('match3

Thanks in advance for your help.

在此先感谢您的帮助。

1 个解决方案

#1


2  

You can use:

您可以使用:

$str = "__('match1') __(\"match2\") do_not_include __('match3')";
preg_match_all('/__\(([\'"])(.*?)\1\)/', $str, $matches);
print_r($matches[2]);

([\'"]) will match either single or double quote and capture it in group #1.

([\'“])将匹配单引号或双引号并在组#1中捕获它。

.*? will match 0 or more characters (non-greedy)

。*?将匹配0个或更多字符(非贪婪)

\1 is back-reference of above captured group to make sure string is closed with same quote on RHS.

\ 1是上面捕获的组的反向引用,以确保字符串在RHS上以相同的引用关闭。

Output:

输出:

Array
(
    [0] => match1
    [1] => match2
    [2] => match3
)

#1


2  

You can use:

您可以使用:

$str = "__('match1') __(\"match2\") do_not_include __('match3')";
preg_match_all('/__\(([\'"])(.*?)\1\)/', $str, $matches);
print_r($matches[2]);

([\'"]) will match either single or double quote and capture it in group #1.

([\'“])将匹配单引号或双引号并在组#1中捕获它。

.*? will match 0 or more characters (non-greedy)

。*?将匹配0个或更多字符(非贪婪)

\1 is back-reference of above captured group to make sure string is closed with same quote on RHS.

\ 1是上面捕获的组的反向引用,以确保字符串在RHS上以相同的引用关闭。

Output:

输出:

Array
(
    [0] => match1
    [1] => match2
    [2] => match3
)