tags:

views:

1213

answers:

4

How can I match (PCRE) everything inbetween two tags?

I tried something like this:

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

But it didn't work out too well for me..

I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.

Thanks

+1  A: 
John Fiala
Can markdown be any more annoying?
John Fiala
+8  A: 
$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>

explanations:

(.*?) = 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 -->'
Owen
A: 

I did not know about non-greedy matching, this will come in handy in the future. Thanks a lot guys.

JamesK89
+1  A: 

Yeah, I didn't know about the non-greedy thing either! Is there a site that explains each modifier?

http://www.regular-expressions.info/ is pretty in depth
Owen