Generating a table of contents with collapsible subsections, PhP or JQuery?
I find your php script incredibly hard to read.  Maintaining this script would surely involve substantial time investment.

You are conducting far too much preg_ surgery on input that can be prepared to be valid html.  Processing html is far more reliable via a proper DOM parsing tool.  My preferred tool is DOMDocument and I often pair it with XPath when it makes node targeting clearer/simpler.

I don't have the time to completely rewrite your script, but that is precisely what I recommend.

You shouldn't ever need to perform "mopping up" of your generated html by throwing some more &lt;/div&gt; in at the end.