miqbal
miqbal

Reputation: 2227

Split string between two delimiters

I'm trying to match a string in a HTML source code with starting <!--sliderStart--> and ending <!--sliderEnd-->

Example1:

<!--sliderStart-->
<p>blah</p>
<p>blah2</p>
<!--sliderEnd-->

Example2:

<!--sliderStart--><p>blah</p><p>blah2</p><!--sliderEnd-->

This is my pattern, but it's not working efficiently:

$pattern = "/<!--sliderStart-->[^\n]+(.*?)<!--sliderEnd-->/";

What's the exact pattern for this matching?

Upvotes: 0

Views: 359

Answers (2)

Palladium
Palladium

Reputation: 3763

Regular expression dots don't match newlines unless you tell them to. You need a s modifier at the end of your regex, like so:

$pattern = '/<!--sliderStart-->(.*?)<!--sliderEnd-->/s';

Upvotes: 3

Joseph Silber
Joseph Silber

Reputation: 219938

Why are you using [^\n]+ in your regex? That tells the regex engine not to match newlines, which you do want to match.

Simply get rid of it, and you're good to go:

$pattern = "/<!--sliderStart-->(.*?)<!--sliderEnd-->/s";

Update: Don't forget the s modifier at the end, so that the . also matches newlines.
Thanks @Palladium.

Upvotes: 4

Related Questions