【问题标题】:Regex - PHP Lookaround正则表达式 - PHP 环顾四周
【发布时间】:2011-01-25 14:09:43
【问题描述】:

我有一个字符串,比如:

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

我知道这是一个奇怪的字符串,但请留在我身边:P

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

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

【问题讨论】:

  • (? 应该可以工作。

标签: php regex preg-match-all


【解决方案1】:

如果您想使用 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)

【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    编辑

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

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

    【讨论】:

    • 使用/__\("(.*?)"\)/然后提取匹配组不是更简单吗?我总是觉得那些后向匹配和前向匹配很难阅读。
    • 为什么,谢谢 Jamie,很高兴知道除了我 2.5 岁的儿子之外,至少还有一个人认为我是这样的人! :)
    • @Greg Hewgill,是的,这也是一种选择。也许对杰米来说更可取。我会尽快编辑。
    • @anomareh,是的,我自己写了一个小工具,可以吐出这样的解释。
    • @Greg Hewgill:是的,使用正则表达式绝对会更简单更好。因为第一个look-behind断言将针对测试字符串的每个位置进行测试。我还将使用否定字符类而不是非贪婪的通用字符表达式:/__\("([^"]*)"\)/.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多