4

我有一个字符串,例如:

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

我知道这是一个奇怪的字符串,但请和我在一起:P

我需要一个正则表达式来查找 __("Look for content here") 之间的内容并将其放入数组中。

即正则表达式会找到“你好吗”和“非常好,谢谢”。

4

2 回答 2

7

试试这个:

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

意思是:

(?<=     # 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

编辑

正如格雷格所提到的:对环视不太熟悉的人,将它们排除在外可能更具可读性。然后匹配所有内容:__("字符串,并将匹配字符串,")的正则表达式包装在括号内以仅捕获这些字符。然后,您将需要获得您的比赛。一个演示:.*?$matches[1]

preg_match_all('/__\("(.*?)"\)/', $foo, $matches);
print_r($matches[1]);
于 2010-03-09T19:15:11.883 回答
2

如果您想使用 Gumbo 的建议,请归功于他的模式:

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

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

除非您也想要完整的字符串结果,否则请务必使用$matches[1]您的结果。

var_dump()$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)
于 2010-03-09T19:50:52.333 回答