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

Time:09-23

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!

CodePudding user response:

Change your Regex to

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

Explanation

<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." ";
  •  Tags:  
  • php
  • Related