We help IT Professionals succeed at work.

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

OneManOneLaptop
OneManOneLaptop used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Try this out:
$result = preg_replace('#(<ul[^>]*>[^<]*<li)#', '$1 class="first"', $source);
$result = preg_replace('#(<li[^>]*)(>[^<]*</li>[^<]*</ul>)#', '$1 class="last"$2', $result);

Open in new window

For the future help and on the fly checking you may find this interesting:
http://gskinner.com/RegExr/
Mike McCrackenSenior Consultant
Most Valuable Expert 2011
Top Expert 2013

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