根据标题标签自动生成嵌套目录 [英] Automatically generate nested table of contents based on heading tags

查看:125
本文介绍了根据标题标签自动生成嵌套目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们当中哪位狡猾的程序员可以向我展示一种优雅的php编码解决方案,该解决方案可以根据页面上的标题标签自动生成嵌套的目录表?

Which one of you crafty programmers can show me an elegant php coded solution for automatically generating a nested table of contents based on heading tags on the page?

因此,我有一个html文档:

So I have a html document thus:

<h1> Animals </h1>

Some content goes here.
Some content goes here.

<h2> Mammals </h2>

Some content goes here.
Some content goes here.

<h3> Terrestrial Mammals </h3>
Some content goes here.
Some content goes here.

<h3> Marine Mammals </h3>
Some content goes here.
Some content goes here.

<h4> Whales </h4>
Some content goes here.
Some content goes here.

更具体地说,我希望链接的目录以嵌套页面的形式出现在同一页面上,这些链接指向同一页面上的标题:

More specifically, I want a linked table of contents in the form of a nested list of links to headings on the same page:

目录(由PHP代码自动生成)

Table of Contents (automatically generated by PHP code)

  1. 动物
  1. 哺乳动物
  1. Terrestrial_Mammals
  2. 海洋哺乳动物
  1. Terrestrial_Mammals
  2. Marine_Mammals
  1. 鲸鱼

推荐答案

我找到了Alex Freeman(

I found this method, by Alex Freeman (http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php):

    preg_match_all('#<h[4-6]*[^>]*>.*?<\/h[4-6]>#',$html_string,$resultats);

    //reformat the results to be more usable
    $toc = implode("\n",$resultats[0]);
    $toc = str_replace('<a name="','<a href="#',$toc);
    $toc = str_replace('</a>','',$toc);
    $toc = preg_replace('#<h([4-6])>#','<li class="toc$1">',$toc);
    $toc = preg_replace('#<\/h[4-6]>#','</a></li>',$toc);

    //plug the results into appropriate HTML tags
    $toc = '<div id="toc"> 
    <p id="toc-header">Table des matières</p>
    <hr />
    <ul>
    '.$toc.'
    </ul>
    </div><br /><br />';

    return $toc;

在HTML中,标头必须写为:

In the HTML, the headers have to be written as:

<h2><a name="target"></a>Text</h2>

这篇关于根据标题标签自动生成嵌套目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆