Regex - PHP Lookaround

I have a line like:

$foo = 'Hello __("How are you") I am __("very good thank you")' 

I know this is a strange line, but stay with me, please: P

I need a regex expression that will search for content between __ ("Search for content here") and put it in an array.

i.e. the regular expression will find "Like you" and "very good thanks."

+4
source share
2 answers

Try the following:

 preg_match_all('/(?<=__\(").*?(?="\))/s', $foo, $matches); print_r($matches); 

which means:

 (?<= # start positive look behind __\(" # match the characters '__("' ) # end positive look behind .*? # match any character and repeat it zero or more times, reluctantly (?= # start positive look ahead "\) # match the characters '")' ) # end positive look ahead 

EDIT

And as Greg said: someone not too familiar with the views may be more readable to leave them. Then you match everything: __(" , string and ") and complete the regular expression that matches the string,. .*? inside brackets to display only those characters. Then you will need to get your matches, although $matches[1] . Demonstration:

 preg_match_all('/__\("(.*?)"\)/', $foo, $matches); print_r($matches[1]); 
+7
source

If you want to use the Gumbo offer, then it credits it for the template:

 $foo = 'Hello __("How are you")I am __("very good thank you")'; preg_match_all('/__\("([^"]*)"\)/', $foo, $matches); 

Be sure to use $matches[1] for your results if you also don't want all string results to be there too.

var_dump() of $matches :

 array 0 => array 0 => string '__("How are you")' (length=16) 1 => string '__("very good thank you")' (length=25) 1 => array 0 => string 'How are you' (length=10) 1 => string 'very good thank you' (length=19) 
+2
source

Source: https://habr.com/ru/post/1303590/


All Articles