3

I've a dynamic menu which looks like

<li class='has-sub'> cat1</li>
<ul>
    <li> test5</li>
    <li class='has-sub'> cat2</li>
    <ul>
        <li> cat9</li>
        <li class='has-sub'> cat7</li>
        <ul>
            <li> cat8</li>
            <li> cat10</li>
            <li> cat1 cat2</li>
        </ul>
    </ul>
</ul>
<li class='has-sub'> cat3</li>
<ul>
    <li> cat5</li>
</ul>

I want to change that to a properly nested navigation menu like

<li class='has-sub'> <a href='#'><span>cat1</span></a>
<ul>
    <li><a href='#'><span> test5</span></a></li>
    <li class='has-sub'><a href='#'><span> cat2</span></a>
    <ul>
        <li> <a href='#'><span>cat9</span></a></li>
        <li class='has-sub'> <a href='#'><span>cat7</span></a>
        <ul>
            <li> <a href='#'><span>cat8</span></a></li>
            <li> <a href='#'><span>cat10</span></a></li>
            <li> <a href='#'><span>cat1 cat2</span></a></li>
        </ul>
        </li>
    </ul>
    </li>
</ul>
</li>
<li class='has-sub'> <a href='#'><span>cat3</span></a>
<ul>
    <li> <a href='#'><span>cat5</span></a></li>
</ul>
</li>

I tried few str_replace but since the list is dynamic It wont work. I'm new to Regex and am not sure how to format this dynamic menu to a properly nested/formatted menu.

Thanks in advance!

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
now-r-never
  • 183
  • 2
  • 4
  • 18
  • I'm sorry, it has! I'll correct it now.. – now-r-never May 07 '14 at 05:38
  • Do you need _only_ a regex solution for this? – AyB May 07 '14 at 05:45
  • @ICanHasCheezburger I learnt regex is good for dynamic things. I'm okay with any other solution if it does proper nesting! – now-r-never May 07 '14 at 05:47
  • @now-r-never: Regex is good for some things, but parsing markup is beyond its capabilities. Regex and markup don't mix well, look into `DOMDocument` instead, to parse the markup – Elias Van Ootegem May 07 '14 at 05:48