DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

5 2 1

Use PHP to generate table of contents from heading tags

Use PHP to generate table of contents from heading tags

I wanted to create a table of contents from the post's heading tags automatically without having to change the headings like adding an id or anchor.

I started to look at existing solutions and came across this custom function on Stackoverflow by sjaak-wish


function generateIndex($html) {
    preg_match_all('/<h([1-6])*[^>]*>(.*?)<\/h[1-6]>/',$html,$matches);

    $index = "<ul>";
    $prev = 2;

    foreach ($matches[0] as $i => $match){

        $curr = $matches[1][$i];
        $text = strip_tags($matches[2][$i]);
        $slug = strtolower(str_replace("--","-",preg_replace('/[^\da-z]/i', '-', $text)));
        $anchor = '<a name="'.$slug.'">'.$text.'</a>';
        $html = str_replace($text,$anchor,$html);

        $prev <= $curr ?: $index .= str_repeat('</ul>',($prev - $curr));
        $prev >= $curr ?: $index .= "<ul>";

        $index .= '<li><a href="#'.$slug.'">'.$text.'</a></li>';

        $prev = $curr;
    }

    $index .= "</ul>";

    return ["html" => $html, "index" => $index];
}

Enter fullscreen mode Exit fullscreen mode

This will generate a list of links based on the headings.

To use the function call it and pass in your content, then specify the array key to use. html for the body and index for the table of contents.

Table of contents:


toc($post->content)['index']
Enter fullscreen mode Exit fullscreen mode

Content:


toc($post->content)['html']
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs