<?php $html = '<h2>Spiders</h2> <h2>Beetles</h2> <h3>External morphology</h3> <h4>Head</h4> <h4>Thorax</h4> <h4>Legs</h4> <h3>Anatomy and physiology</h3> <h2>Ants</h2>'; preg_match_all('/<h(\d)>([^<]+)/', $html, $matches); $cdepth = $matches[1][0] - 1; foreach ($matches[1] as $key => $depth) { if ($depth > $cdepth) { echo "\n" . str_repeat(' ', $cdepth * 4) . "<ol>\n"; } elseif ($depth < $cdepth) { echo "</li>\n" . str_repeat(' ', $depth * 4) . "</ol>\n" . str_repeat(' ', $depth * 4) . "</li>\n"; } else { echo "</li>\n"; } $cdepth = $depth; echo str_repeat(' ', $cdepth * 4) . "<li><a href=\"{$matches[2][$key]}\">{$matches[2][$key]}</a>"; } while ($cdepth-- >= $matches[1][0]) { echo "</li>\n" . str_repeat(' ', $cdepth * 4) . "</ol>\n"; }
You have javascript disabled. You will not be able to edit any code.