I have a hard time figuring out how I can get multiple headings and the first paragraph for that heading. In this case I only need the h3 titles and the following paragraph for each.
Example code
function everything_in_tags($string, $tagname)
{
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match($pattern, $string, $matches);
return $matches[1];
}
$tagname = "h3";
$string = "<h1>This is my title</h1>
<p>This is a text right under my h1 title.</p>
<p>This is some more text under my h1 title</p>
<h2>This is my level 2 heading</h2>
<p>This is text right under my level 2 heading</p>
<h3>First h3</h3>
<p>First paragraph for the first h3</p>
<h3>Second h3</h3>
<p>First paragraph for the second h3</p>
<h3>Third h3</h3>
<p>First paragraph for the third h3</p>
<p>Second paragraph for the third h3</p>
<h2>This is my level 2 heading</h2>
<p>This is text right under my level 2 heading</p>";
//OUTPUT: First h3
echo everything_in_tags($string, $tagname);
I would like to implement a foreach loop - but that requires that the above is working as expected.
foreach ($headings as $heading && $paragraphs as $paragraph) {
echo "<h3>".$heading."</h3>";
echo "<p>".$paragraph."</p>";
}
//Expected output:
//<h3>First h3</h3>
//<p>First paragraph for the first h3</p>
//<h3>Second h3</h3>
//<p>First paragraph for the second h3</p>
//<h3>Third h3</h3>
//<p>First paragraph for the third h3</p>
So in above example I can get the first h3. But after a lot of reading, I can't seem to find out how to get all the h3's and the first paragraphs for each as well.
If anyone can point me in the right direction and explain to me how to do this I would really appreciate it. Thank you.