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> <p>something</p> <h2>heading 2</h2> <p>something</p> <h2>heading 3</h2> <p>something</p>
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); print_r($found);
Thanks for any help for a beginner!
Change your Regex to
<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 as $a) echo $a." ";
Answered By – Tushar