Forum Moderators: coopster

Message Too Old, No Replies

preg match help

pattern match php preg_match

         

jpl80

3:28 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



I would like to use preg_match() to get everything between two html comments (from an external html file):


<!--begin_first-->
<div id="firstp">
<p>First paragraph</p>
</div>
<!--end_first-->

jpl80

5:16 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



I found this snippet that does exactly what I want it to, but when I plug in my html comments in the place of this tag, it stops working.

Are you supposed to escape any of the characters in an html comment?

preg_match("/<title>(.*)<\/title>/i", $source, $tag_contents);
$title = $tag_contents[1];
echo $title;

cameraman

5:27 pm on Nov 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



In this:
preg_match("/<title>(.*)<\/title>/i", $source, $tag_contents);

the backslash at <\/title> is escaping the /. If you're leaving that out, so you wind up with:

preg_match("/<!--begin_first-->(.*)<!--end_first-->/i", $source, $tag_contents);

then it should work. If you're leaving that backslash in, that's where the problem is.

jpl80

6:51 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



Yes, I left the escape character out. This is what I have. I cannot figure out why it won't work.


preg_match("/<!--beginfirst-->(.*)<!--endfirst-->/i", $source, $tag_contents);
$title = $tag_contents[1];
echo $title;

my html looks like this:


<div id="content">
<a name="skip"></a>
<!--beginfirst-->
<div id="first_learn">
<p>First paragraph from learn.html.</p>
</div>
<!--endfirst-->
<p>Maecenas mattis varius lorem.</p>
</div>
<!--end #content-->

PHP_Chimp

7:06 pm on Nov 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



preg_match("/<!--beginfirst-->(.*)<!--endfirst-->/i", $source, $tag_contents);
$title = $tag_contents[1];
echo $title;

What are you using as $source?

jpl80

7:20 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



$source is:

$source = file_get_contents("learn.html");

And I know that works because when I plug in another tag, such as: <title>, I get the pages title.

PHP_Chimp

7:36 pm on Nov 27, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try -

preg_match("/<!--beginfirst-->(.*)<!--endfirst-->/is", $source, $tag_contents);
$title = $tag_contents[1];
echo $title;

As without the s modifier the . doesnt match the \n character.

jpl80

7:37 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



perfect. Thank you so much.