Voting

: one plus six?
(Example: nine)

The Note You're Voting On

William Barry
17 years ago
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved. I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.

This was my alternative solution, and it seems to work well:

<?php

function stripNestedLists($str)
{
$str2 = $str;
$lastStr = $str2;

do
{
// Find the first closing ul
$cul = strpos($str2, '</ul>');
$ul = 0;
$lastUL = 0;
do
{
// Find the next opening ul
$lastUL = $ul;
$ul = strpos($str2, '<ul', $ul+1);
}
while (
$ul !== false && $ul < $cul);

$lastStr = $str2;
$str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
$str2 = trim($str2);
}
while (
strlen($str2) > 0);

return
$lastStr;
}

?>

Hope this helps someone.

<< Back to user notes page

To Top