使用正则表达式匹配两个标签之间的所有内容?

Jam*_*K89 4 html php regex tags

如何在两个标签之间匹配(PCRE)所有内容?

我试过这样的事情:

<! - \S*LoginStart\S* - >(.*)<! - \S*LoginEnd\S* - >

但它对我来说效果不佳..

我对正则表达式有点新意,所以我希望有人能够向我解释如何实现这一点,如果它可以用正则表达式来实现的话.

谢谢

Owe*_*wen 12

$string = '<!-- LoginStart --><div id="stuff">text</div><!-- LoginEnds -->';
$regex = '#<!--\s*LoginStart\s*-->(.*?)<!--\s*LoginEnds\s*-->#s';

preg_match($regex, $string, $matches);

print_r($matches); // $matches[1] = <div id="stuff">text</div>
Run Code Online (Sandbox Code Playgroud)

解释:

(.*?) = non greedy match (match the first <!-- LoginEnds --> it finds
    s = modifier in $regex (end of the variable) allows multiline matches
        such as '<!-- LoginStart -->stuff
                 more stuff
                 <!-- LoginEnds -->'
Run Code Online (Sandbox Code Playgroud)