如何在WordPress中使用<h2>标记获取所有内容? [重复]

This question already has an answer here:

Sample Content:

<h2 id="h2-1">H2 Heading (1)</h2>
<p>Lorem ipsum dolor sit amet consectetur ...</p>
<h3 id="h3-1">H3 Heading</h3>
<h2 id="h2-2">H2  Heading (2)</h2>

What I'm trying to achieve:

<ul>
  <li><a href='#h2-1'>H2 Heading (1)</a></
  <li><a href='#h2-2'>H2 Heading (2)</a></li>
</ul>

I knew it can be done with a regex function but I don't know how to finish the function. Here's what I have done so far:

function table_of_contents() {
    $content = get_post_field( 'post_content', $post->ID );
    $tags = preg_match_all( '#<h2>(.*?)</h2>#', $content, $matches );

    return $tags;
}
</div>

You can use a Regex like this:

<?php
$content = '<h2 id="h2-1">H2 Heading (1)</h2>
<p>Lorem ipsum dolor sit amet consectetur ...</p>
<h3 id="h3-1">H3 Heading</h3>
<h2 id="h2-2">H2  Heading (2)</h2>';

preg_match_all( '@<h2.*?>(.*?)<\/h2>@', $content, $matches );
$tag = $matches[1];
var_dump($tag);

Output:

array(2) {
  [0]=>
  string(14) "H2 Heading (1)"
  [1]=>
  string(15) "H2  Heading (2)"
}

Details at regex101: https://regex101.com/r/RNeVI2/1