Skip to content

Instantly share code, notes, and snippets.

@arterm-sedov
Created August 18, 2023 09:39
Show Gist options
  • Save arterm-sedov/1a63ce4ebc4deaf3cd3f3a3b194f2c81 to your computer and use it in GitHub Desktop.
Save arterm-sedov/1a63ce4ebc4deaf3cd3f3a3b194f2c81 to your computer and use it in GitHub Desktop.
phpkb automatic TOC generation
<?php
function TableOfContents($depth)
{
$html_string = Articles_Detail('All');
//get the headings down to the specified depth
$pattern = '/<h[2-'.$depth.']+ id=".+"[^>]*>.*?<\/h[2-'.$depth.']>/';
$whocares = preg_match_all($pattern,$html_string,$winners);
//reformat the results to be more usable
$heads = implode("\n",$winners[0]);
$heads = preg_replace('/<h[1-'.$depth.'] id="(.+)">/','<li> <a href="#$1">',$heads);
$heads = preg_replace('/<\/h[1-'.$depth.']>/','</a></li>',$heads);
//plug the results into appropriate HTML tags
$contents = '<div class="mce-toc" style="display: none;"
}>
<h2 id="toc-heading">На этой странице</h2>
<ul>
'.$heads.'
</ul>
</div>';
echo $contents;
}
?>
<?php TableOfContents(3); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment