首页 文章

在php中创建目录

提问于
浏览
0

我希望在php中创建一个非常简单,非常基本的嵌套目录,它可以获得所有h1-6并适当地缩进内容 . 这意味着,如果我有类似的东西:

<h1>content</h1>
<h2>more content</h2>

我应该得到:

content
    more content.

我知道这将是css创建缩进,这很好,但我如何创建一个目录与页面上的内容的工作链接?

apparently 很难理解我的要求......

我要求一个函数读取一个html文档并拉出所有h1-6并制作一个目录 .

1 回答

  • 0

    为此,您只需在HTML代码中搜索标记即可 .

    我写了两个函数(PHP 5.4.x) .

    第一个返回一个数组,其中包含目录的数据 . 数据只是它自己的 Headers ,标签的id(如果你想使用锚点)和内容的子表 .

    function get_headlines($html, $depth = 1)
    {
        if($depth > 7)
            return [];
    
        $headlines = explode('<h' . $depth, $html);
    
        unset($headlines[0]);       // contains only text before the first headline
    
        if(count($headlines) == 0)
            return [];
    
        $toc = [];      // will contain the (sub-) toc
    
        foreach($headlines as $headline)
        {
            list($hl_info, $temp) = explode('>', $headline, 2);
            // $hl_info contains attributes of <hi ... > like the id.
            list($hl_text, $sub_content) = explode('</h' . $depth . '>', $temp, 2);
            // $hl contains the headline
            // $sub_content contains maybe other <hi>-tags
            $id = '';
            if(strlen($hl_info) > 0 && ($id_tag_pos = stripos($hl_info,'id')) !== false)
            {
                $id_start_pos = stripos($hl_info, '"', $id_tag_pos);
                $id_end_pos = stripos($hl_info, '"', $id_start_pos);
                $id = substr($hl_info, $id_start_pos, $id_end_pos-$id_start_pos);
            }
    
            $toc[] = [  'id' => $id,
                        'text' => $hl_text,
                        'sub_toc' => get_headlines($sub_content, $depth + 1)
                    ];
    
        }
    
        return $toc;
    }
    

    secound返回一个字符串,用html格式化toc .

    function print_toc($toc, $link_to_htmlpage = '', $depth = 1)
    {
        if(count($toc) == 0)
            return '';
    
        $toc_str = '';
    
        if($depth == 1)
            $toc_str .= '<h1>Table of Content</h1>';
    
        foreach($toc as $headline)
        {
            $toc_str .= '<p class="headline' . $depth . '">';
            if($headline['id'] != '')
                $toc_str .= '<a href="' . $link_to_htmlpage . '#' . $headline['id'] . '">';
    
            $toc_str .= $headline['text'];
            $toc_str .= ($headline['id'] != '') ? '</a>' : '';
            $toc_str .= '</p>';
    
            $toc_str .= print_toc($headline['sub_toc'], $link_to_htmlpage, $depth+1);
        }
    
        return $toc_str;
    }
    

    这两个功能都远非完美,但它们在我的测试中运行良好 . 随意改进它们 .

    注意: get_headlines 不是解析器,因此它不适用于错误的html代码而只是崩溃 . 它也只适用于小写 <hi> -tags

相关问题