auto generate table of contents php

Solutions on MaxInterview for auto generate table of contents php by the best coders in the world

showing results for - "auto generate table of contents php"
Elea
13 Mar 2020
1<?php
2	function TableOfContents($depth)
3	/*AutoTOC function written by Alex Freeman
4	* Released under CC-by-sa 3.0 license
5	* http://www.10stripe.com/  */
6	{
7	$filename = __FILE__;
8	//read in the file
9	$file = fopen($filename,"r");
10	$html_string = fread($file, filesize($filename));
11	fclose($file);
12 
13	//get the headings down to the specified depth
14	$pattern = '/<h[2-'.$depth.']*[^>]*>.*?<\/h[2-'.$depth.']>/';
15	$whocares = preg_match_all($pattern,$html_string,$winners);
16 
17	//reformat the results to be more usable
18	$heads = implode("\n",$winners[0]);
19	$heads = str_replace('<a name="','<a href="#',$heads);
20	$heads = str_replace('</a>','',$heads);
21	$heads = preg_replace('/<h([1-'.$depth.'])>/','<li class="toc$1">',$heads);
22	$heads = preg_replace('/<\/h[1-'.$depth.']>/','</a></li>',$heads);
23 
24	//plug the results into appropriate HTML tags
25	$contents = '<div id="toc"> 
26	<p id="toc-header">Contents</p>
27	<ul>
28	'.$heads.'
29	</ul>
30	</div>';
31	echo $contents;
32	}
33 ?>