代码之家  ›  专栏  ›  技术社区  ›  gurehbgui

Regex帮助(PHP)在两个字符串之间查找和选择字符

  •  1
  • gurehbgui  · 技术社区  · 14 年前

    我需要你的帮助。例如,我有一个有许多空白和新行的长文本,我需要找到并选择两个字符串之间的所有。 例子:

    iojge test rgej <foo>
    ferfe 098n34hjlrej
    fefe <end
    

    我想找出测试和结束之间的所有关系:

     rgej <foo>
    ferfe 098n34hjlrej
    fefe <
    

    我该怎么做?

    4 回复  |  直到 14 年前
        1
  •  4
  •   Colin Hebert    14 年前

    preg_match("/test(.*?)end/s", $yourString, $matches);
    print_r($matches);
    
        2
  •  2
  •   Daniel Vandersluis    14 年前

    你可以用两个 lookarounds 以及 /s (单线) modifier dot 匹配新行,寻找两个单词之间的所有内容:

    /(?<=test).*(?=end)/s
    

    (?<=    # open a positive lookbehind
      test  # match 'test'
    )       # close the lookbehind
    .*      # match as many characters as possible (including newlines because of the \s modifier)
    (?=     # open a positive lookahead
     end    # match 'end'
    )       # close the lookahead
    

    lookarounds将允许您断言模式必须由您的两个单词锚定,但是由于lookarounds没有捕获,因此只有单词之间的所有内容将由 preg_match . 一个旁观者看 判断断言是否通过的当前位置;向前看 当前位置。

    greedy 默认情况下 .* end .* lazy (换句话说,它将匹配 通过将其更改为 .*? (即。 /(?<=test).*?(?=end)/s

        3
  •  1
  •   codaddict    14 年前

    $arr1 = explode("test",$input);
    $arr2 = explode("end",$arr1[1]);
    $result = $arr2[0];
    
        4
  •  0
  •   Gumbo    14 年前

    $str = 'iojge test rgej <foo>
    ferfe 098n34hjlrej
    fefe <end';
    $start = 'test';
    $end = 'end';
    if (($startPos = strpos($str, $start)) !== false && ($endPos = strpos($str, $end, $startPos+=strlen($start))) !== false) {
        // match found
        $match = substr($str, $startPos, $endPos-$startPos);
    }