Avatar of OneManOneLaptop
OneManOneLaptop
 asked on

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

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>

Open in new window


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>

Open in new window


I would expect that this has been done before but I cant seem to find a goo starting point.
Any help would be appreciated.
AlgorithmsRegular ExpressionsWeb Development

Avatar of undefined
Last Comment
Mike McCracken

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
kaufmed

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Lukasz Chmielewski

For the future help and on the fly checking you may find this interesting:
http://gskinner.com/RegExr/
Mike McCracken

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck