regexp target last main li in list

Posted by veilig on Stack Overflow See other posts from Stack Overflow or by veilig
Published on 2010-06-07T20:20:20Z Indexed on 2010/06/07 20:22 UTC
Read the original article Hit count: 185

Filed under:
|
|

I need to target the starting tag of the last top level LI in a list that may or may-not contain sublists in various positions - without using CSS or Javascript.

Is there a simple/elegant regexp that can help with this? I'm no guru w/ them, but it appears the need for greedy/non-greedy selectors when I'm selecting all the middle text (.*) / (.+) changes as nested lists are added and moved around in the list - and this is throwing me off.

$pattern = '/^(<ul>.*)<li>(.+<\/li><\/ul>)$/';
$replacement = '$1<li id="lastLi">$3';

Perhaps there is an easier approach?? converting to XML to target the LI and then convert back?

ie: Single Element

<ul>
    <li>TARGET</li>
</ul>

Multiple Elements

<ul>
    <li>foo</li>
    <li>TARGET</li>
</ul>

Nested Lists before end

<ul>
    <li>
        foo
        <ul>
            <li>bar</li>
        </ul>
    <li>
    <li>TARGET</li>
</ul>

Nested List at end

<ul>
    <li>foo</li>
    <li>
        TARGET
        <ul>
            <li>bar</li>
        </ul>
    </li>
</ul>

© Stack Overflow or respective owner

Related posts about php

Related posts about html