Find all text occurrences between <h2></h2>


I want to auto generate a table of content out of a html string with all h2 headings and need to put them in an array for that reason.

I have a $text string with the formatted html inside:

<h2>heading 1</h2>
<h2>heading 2</h2>
<h2>heading 3</h2>

How can I extract all the headings inside h2 into an array?

I found out that I need regex, maybe preg_match_all.

I tried this, but it doesn’t work:

preg_match_all("<h2>(.*?)</h2>", $text, $found);

Thanks for any help for a beginner!


Change your Regex to

preg_match_all('#<h2.*?>(.*?)</h2>#i',$text, $found);


<h2.*?> - ignore the classes/attributes in the tag if any
(.*?)   - capture everything
</h2>   - match end tag
i       - ignore case 

Then Loop through Array and print values

foreach ($found[1] as $a) 
  echo $a." ";

Answered By – Tushar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published