Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match everything inbetween two tags with Regular Expressions?

Tags:

html

regex

php

tags

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

like image 540
JamesK89 Avatar asked Dec 14 '22 06:12

JamesK89


2 Answers

$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 -->'
like image 86
Owen Avatar answered Dec 15 '22 20:12

Owen


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.

like image 30
John Fiala Avatar answered Dec 15 '22 18:12

John Fiala