如何在正则表达式中匹配字符串后跟重复模式?

时间:2017-03-16 13:10:20

标签: php regex

我正在寻找匹配以下模式的正则表达式:

--header--任何文字-pre-任何文字-/pre- -pre-任何文字-/pre-

例如:以下文字

--comment--
list of comments
-pre-
comment 1
-/pre-

-pre-
comment 2
-/pre-

--Answers--
list of Answers
-pre-
Answer 1
-/pre-

-pre-
Answer 2
-/pre-
应用正则表达式时,

应返回如下:

Array
(
    [comments] => Array
        (
            [0] => comment 1
            [1] => comment 2
        )

    [answers] => Array
        (
            [0] => answer 1
            [1] => answer 2
        )

)

我尝试了以下正则表达式--(.*?)--.*?(-pre-(.*?)-\/pre-)+,但只匹配comment 1answer 1

示例代码: https://regex101.com/r/59OKzs/1

2 个答案:

答案 0 :(得分:0)

正则表达式:

(?:--([^-]+)--(?:(?!-pre-).)+|(?!\A)\G)\s*-pre-\s*((?:(?!-/pre-).)*)-/pre-\K

Live demo

PHP:

preg_match_all('~(?:--([^-]+)--(?:(?!-pre-).)+|(?!\A)\G)\s*-pre-\s*((?:(?!-/pre-).)*)-/pre-\K~s', $str, $matches, PREG_SET_ORDER);

要整合适当的键和值:

// Filter empty values
$matches = array_map(function($v) {
    return array_values(array_filter($v));
}, $matches);

// Initialize two variables which we use them soon
$index = null; $finalArray = [];

// Iterate over recent matches in order to apply keys
array_map(function($array) use (&$index, &$finalArray) {
    count($array) == 2 ? ($index = $array[0]) && ($finalArray[$index][] = $array[1]) : $finalArray[$index][] = $array[0];
}, $matches);

// Print out
print_r($finalArray);

PHP live demo

答案 1 :(得分:0)

也许将preg_match_all/--(.*?)--.*?-pre-\n*(.*?)\n*-\/pre-.*?-pre-\n*(.*?)\n*-\/pre-/s

一起使用
preg_match_all('/--(.*?)--.*?-pre-\n*(.*?)\n*-\/pre-.*?-pre-\n*(.*?)\n*-\/pre-/s',$string,$matches,   PREG_SET_ORDER);

for($i=0;$i<count($matches);$i++)
    $output[$matches[$i][1]] = array($matches[$i][2], $matches[$i][3]);

print_r($output);