troubleshooting Question

PHP Regular Expression To Add First And Last Classes To A List

Avatar of OneManOneLaptop
OneManOneLaptop asked on
Web DevelopmentAlgorithmsRegular Expressions
3 Comments1 Solution298 ViewsLast Modified:
Given a nested list of HTML as follows
<ul>
    <li>Coffee
        <ul>
            <li>Coffee</li>
            <li>Tea    
                <ul>
                    <li>Coffee</li>
                    <li>Tea</li>
                    <li>Milk</li>
                </ul>
            </li>
            <li>Milk</li>
        </ul>
    </li>
    <li>Tea</li>
    <li>Water</li>
    <li>Milk 
        <ul>
            <li>Coffee</li>
            <li>Tea</li>
            <li>Milk</li>
        </ul>
    </li>
    <li>Tea</li>
    <li>Coke</li>
    <li>Lemonade</li>
</ul>

The code above is stored in a php string.
I'm trying to construct a PHP regular expression to add CSS classes the the first and last elements of each set of <LI> elements so that each set of <LI> that are nested also have their own first and last classes.

Desired output

<ul>
    <li class='first'>Coffee
        <ul>
            <li  class='first'>Coffee</li>
            <li>Tea    
                <ul>
                    <li  class='first'>Coffee</li>
                    <li>Tea</li>
                    <li class='last'>Milk</li>
                </ul>
            </li>
            <li class='last'>Milk</li>
        </ul>
    </li>
    <li>Tea</li>
    <li>Water</li>
    <li>Milk 
        <ul>
            <li  class='first'>Coffee</li>
            <li>Tea</li>
            <li class='last'>Milk</li>
        </ul>
    </li>
    <li>Tea</li>
    <li>Coke</li>
    <li class='last'>Lemonade</li>
</ul>

I would expect that this has been done before but I cant seem to find a goo starting point.
Any help would be appreciated.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 3 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros