views:

42

answers:

4

Hi,

I'm trying to replace all ul tags with a level0 class, something like this:

<ul>
    <li>Test
         <ul class="level0">
           ...
         </ul>
     </li>
</ul>

would be processed to

<ul>
    <li>Test</li>
</ul>

I tried

$_menu = preg_replace('/<ul class="level0">(.*)<\/ul>/iU', "", $_menu); 

but it's not working, help?

Thanks.

Yehia

A: 

try /mis instead of /iU

GameBit
if you use /mis instead of /iU it "works" but it also also still cuts down everything after the ul element, cause "you" tell him to take anything (.*).
Hannes
ofcourse it does, because you teling him to do that... change (.*) to (.*?)
GameBit
A: 

Your code works fine- except you are passing $_menu as a string containing characters other than those you are doing a preg_replace against, despite the fact visually it looks fine. The string is also containing tabs, breaks and spaces- which the RegEx isnt looking for. You can resolve this using:

(for example)

$_menu='<ul>
    <li>Test
         <ul class="level0">
           ...
         </ul>
     </li>
</ul>
';


$breaks = array("
", "\n", "\r", "chr(13)", "\t", "\0", "\x0B");
$_menu=str_replace($breaks,"",$_menu);

$_menu = preg_replace('/<ul class="level0">(.*)<\/ul>/iU', "", $_menu); 
Ergo Summary
+6  A: 

I am sure this is a duplicate, but anyway, here is how to do it with DOM

$dom = new DOMDocument;                          // init new DOMDocument
$dom->loadHTML($html);                           // load HTML into it
$xpath = new DOMXPath($dom);                     // create a new XPath
$nodes = $xpath->query('//ul[@class="level0"]'); // Find all UL with class
foreach($nodes as $node) {                       // Iterate over found elements
    $node->parentNode->removeChild($node);       // Remove UL Element
}
echo $dom->saveHTML();                           // output cleaned HTML
Gordon
+1, if your class attribute can contain multiple classes use `//ul[contains(@class,'level0')]` (although that would still break on `prefixlevel0` or `level0suffix`).
Wrikken
hooray for xpath
Hannes
A: 

try

$str ='<ul>
    <li>Test
         <ul class="level0">
          tsts
         </ul>
     </li>
</ul>
';
//echo '<pre>';
$str = preg_replace(array("/(\s\/\/.*\\n)/","/(\\t|\\r|\\n)/",'/<!--(.*)-->/Uis','/>\\s+</'),array("","","",'><'),$str);
echo preg_replace('/<ul class="level0">(.*)<\/li>/',"</li>",trim($str));
Yogesh