Question

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

Was it helpful?

Solution

$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 -->'

OTHER TIPS

PHP and regex? Here's some suggestions:

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

Might be better - the U capitalized makes the regex non-greedy, which means it'll stop at the first <!-- that may work. But the important one is the s, which tells the regex to match a newline with the . character.

Depending on how certain you are on the capitalization, adding an i at the end will make the regex search case-insensitive.

i have tried Owen's answer but its fails for the conditions like

<!-- LoginStart --><div id="stuff">text</div><!-- LoginEnds -->"DONT MIND THIS"<!-- LoginStart --><div id="stuff">text</div><!-- LoginEnds -->

This includes the line "DONT MIND THIS" also, that is it covers all the contents within first <!-- LoginStart --> and last <!-- LoginEnds --> tag

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top