Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - PHP Lookaround

I have a string, such as this:

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

I know it's a strange string, but stay with me please :P

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

i.e. the regular expression would find "How are you" and "very good thank you".

like image 228
Flukey Avatar asked Jan 22 '23 11:01

Flukey


2 Answers

Try this:

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 mentioned: someone not too familiar with look-arounds, it might be more readable to leave them out. You then match everything: __(", the string and ") and wrap the regex that matches the string, .*?, inside parenthesis to capture only those characters. You will then need to get your matches though $matches[1]. A demo:

preg_match_all('/__\("(.*?)"\)/', $foo, $matches);
print_r($matches[1]);
like image 177
Bart Kiers Avatar answered Jan 25 '23 01:01

Bart Kiers


If you want to use Gumbo's suggestion, credit goes to him for the pattern:

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

preg_match_all('/__\("([^"]*)"\)/', $foo, $matches);

Make sure to use $matches[1] for your results unless you want the full string results 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)
like image 20
anomareh Avatar answered Jan 25 '23 00:01

anomareh