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

这个问题已经在这里有了答案:

使用php从h1标签获取所有值(4个答案)

2年前关闭。

样本内容:

<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>

我想要达到的目标:

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

我知道可以用正则表达式函数来完成, 但是我不知道如何完成该函数。到目前为止, 这是我所做的:

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

    return $tags;
}

#1


你可以像这样使用正则表达式:

<?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);

输出如下:

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

regex101上的详细信息:https://regex101.com/r/RNeVI2/1

来源:

https://www.srcmini02.com/63330.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_37637.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?