Reputation: 173
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
Upvotes: 4
Views: 4621
Reputation: 4581
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.
Upvotes: 1
Reputation: 1873
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
Upvotes: 0
Reputation: 84493
$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 -->'
Upvotes: 12