I found this method, Alex Freeman ( http://www.10stripe.com/articles/automatically-generate-table-of-contents-php.php ):
preg_match_all('#<h[4-6]*[^>]*>.*?<\/h[4-6]>#',$html_string,$resultats);
$toc = implode("\n",$resultats[0]);
$toc = str_replace('<a name="','<a href="#',$toc);
$toc = str_replace('</a>','',$toc);
$toc = preg_replace('#<h([4-6])>#','<li class="toc$1">',$toc);
$toc = preg_replace('#<\/h[4-6]>#','</a></li>',$toc);
$toc = '<div id="toc">
<p id="toc-header">Table des matières</p>
<hr />
<ul>
'.$toc.'
</ul>
</div><br /><br />';
return $toc;
In HTML, headers should be written as:
<h2><a name="target"></a>Text</h2>