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
https://forums.phpfreaks.com/topic/125964-preg_match-help-with-newlines/
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

$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.

<?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;

preg_match_all('!<h1>([^<]+)</h1>!', $str, $matches);
print_r($matches);

 

Just take $matches[1][1].

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.