简体   繁体   中英

PHP Regular expression to find string enclosed in __("STRING_TO_EXTRACT")

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.

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.

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

Thanks in advance for your help.

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.

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

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

Output:

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

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