donglu3243 2018-11-24 09:02
浏览 49

如何在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>
  • 写回答

1条回答 默认 最新

  • douzhe1264 2018-11-24 09:51
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”