camoo/toc

从文本生成目录

维护者

详细信息

github.com/camoo/toc

主页

源码

问题

安装: 24

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

公开问题: 0

类型:项目

1.0 2020-03-06 21:12 UTC

This package is auto-updated.

Last update: 2024-09-07 07:19:20 UTC


README

Build Status

特性

此包可以解析带有 H 标签的 Html 内容,并在内容中生成带有锚点的目录。

安装

  composer require camoo/toc

使用

        $toc = new TableOfContents('<h1>Html Content</h1>');
		// get only table of contents part
        $onlyTableOfContents = $toc->getTableOfContents();

		// get full content with table of contents included
        $fullContent = $toc->getContent();

基本示例

$htmlContent = <<<END
    <h1>This is a header tag h1</h1>
    <p>Lorum ipsum doler sit amet</p>
    <h2>This is a header tag h2</h2>
    <p>Foo Bar</p>
    <h3>This is a header tag h3</h3>
END;

$toc = new TableOfContents($htmlContent);

$fullHtml  = $toc->getContent();


echo $fullHtml;

这将产生以下输出

<h1 id="toc-header">Table of Contents</h1>
<hr />
<div>
    <ul>
        <li>
            <a href="#toc-0">This is a header tag h1</a>
            <ul>
                <li>
                    <a href="#toc-1">This is a header tag h2</a>
                    <ul>
                        <li><a href="#toc-2">This is a header tag h3</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</div>
<hr />
<h1><a href="#" name="toc-0"></a>This is a header tag h1</h1>
<p>Lorum ipsum doler sit amet</p>
<h2><a href="#" name="toc-1"></a>This is a header tag h2</h2>
<p>Foo Bar</p>
<h3><a href="#" name="toc-2"></a>This is a header tag h3</h3>

指定要包含的标题级别

您可以选择仅包括 TOC 中的特定 h1...h6 标题级别。默认情况下,脚本解析 h1-h6。为此,将可选参数 $depth 传递给构造函数

$htmlContent = '<h1>Tester</h1><b>Bold</b><h2>Sub-Test</h2><a href="#">link</a><h3>3rd Level</h3><h4>4rd level</h4>';

// Get TOC using h1-h3
$toc = new TableOfContents($htmlContent,3);