Jump to content

preg_match help with newlines


hlstriker

Recommended Posts

I'm trying to better understand preg_match. I've searched all over the internet looking at examples and such but everytime I try to create my own match it doesn't work how I intended.

 

In this example I'm trying to get the text inside of the second <h1></h1> tag.

<h2>Some text</h2>
<h1>More text on a new line with a tab</h1>
<h1>Here is the second h1</h1>
	<h3>Some more tabs added</h3>

 

The pattern I'm using is the following:

$pattern = "~</h1>(.*)<h1>(.+?)</h1>~msU";

 

I was thinking this is how it would work:

</h1> = Starting point

(.*)<h1> = Go through code until it finds <h1>

(.+?)</h1> = Read the text until </h1> is found.

 

So shouldn't $matches[2] equal the second parenthesized sub-pattern which would be "Here is the second h1"?

Link to comment
Share on other sites

<pre><?php

$str = <<<STR
<h2>Some text</h2>
<h1>More text on a new line with a tab</h1>
<h1>Here is the second h1</h1>
	<h3>Some more tabs added</h3>
STR;

$pattern = "~</h1>(.*)<h1>(.+?)</h1>~msU";

preg_match( $pattern, $str, $matches );

echo $matches[2];

?></pre>

 

Outputs:

 

Here is the second h1

 

So it works for me. PHP5.2.6 Apache2.2.8

Link to comment
Share on other sites

$str = <<<STR
<h2>Some text</h2>
<h1>More text on a new line with a tab</h1>
<h1>Here is the second h1</h1>
	<h3>Some more tabs added</h3>
STR;
preg_match('#</h1>\r\n<h1>([^>]+)</h1>#', $str, $match);
echo $match[1];

 

ouputs:

Here is the second h1

 

Something tells me though that my solution could also be improved on.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.