I have a string variable that contains a lot of HTML markup and I want to get the last <li>
element from it.
Im using something like:
$markup = "<body><div><li id='first'>One</li><li id='second'>Two</li><li id='third'>Three</li></div></body>";
preg_match('#<li(.*?)>(.*)</li>#ims', $markup, $matches);
$lis = "<li ".$matches[1].">".$matches[2]."</li>";
$total = explode("</li>",$lis);
$num = count($total)-2;
echo $total[$num]."</li>";
This works and I get the last <li>
element printed. But I cant understand why I have to subtract the last 2 indexes of the array $total
. Normally I would only subtract the last index since counting starts on index 0. What im i missing?
Is there a better way of getting the last <li>
element from the string?