Link to home
Start Free TrialLog in
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.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For the future help and on the fly checking you may find this interesting:
http://gskinner.com/RegExr/
Avatar of Mike McCracken
Mike McCracken

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.