正则表达式 - PHP外观

Flu*_*key 4 php regex preg-match-all

我有一个字符串,例如:

$foo = 'Hello __("How are you") I am __("very good thank you")'
Run Code Online (Sandbox Code Playgroud)

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

我需要一个正则表达式来查找__("在这里查找内容")之间的内容并将其放在一个数组中.

即正则表达式会找到"你好吗"和"非常好,谢谢你".

Bar*_*ers 7

试试这个:

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

意思是:

(?<=     # 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
Run Code Online (Sandbox Code Playgroud)

编辑

而正如格雷格所说:有些人不太熟悉环顾四周,将它们排除在外可能更具可读性.然后,您匹配的一切:__("中,"),并包裹了相匹配的正则表达式的字符串,.*?,括号内为仅捕捉这些字符.然后你需要得到你的比赛$matches[1].演示:

preg_match_all('/__\("(.*?)"\)/', $foo, $matches);
print_r($matches[1]);
Run Code Online (Sandbox Code Playgroud)

  • @Greg Hewgill:是的,使用你的正则表达式绝对会更简单,更好.因为将针对测试字符串的每个位置测试第一个后视断言.我也会使用一个否定的字符类而不是一个非贪婪的通用字符表达式:`/ __ \("([^"]*)"\)/`. (2认同)