hlstriker Posted September 26, 2008 Share Posted September 26, 2008 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 More sharing options...
discomatt Posted September 26, 2008 Share Posted September 26, 2008 <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 https://forums.phpfreaks.com/topic/125964-preg_match-help-with-newlines/#findComment-651390 Share on other sites More sharing options...
nrg_alpha Posted September 26, 2008 Share Posted September 26, 2008 $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 https://forums.phpfreaks.com/topic/125964-preg_match-help-with-newlines/#findComment-651433 Share on other sites More sharing options...
DarkWater Posted September 26, 2008 Share Posted September 26, 2008 <?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]. Link to comment https://forums.phpfreaks.com/topic/125964-preg_match-help-with-newlines/#findComment-651494 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.