Yehia A.Salam
Yehia A.Salam

Reputation: 2078

Replace UL tags with specific class

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

Upvotes: 0

Views: 1790

Answers (4)

Nik
Nik

Reputation: 4075

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));

Upvotes: 0

SW4
SW4

Reputation: 71160

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); 

Upvotes: 0

Gordon
Gordon

Reputation: 316999

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

Upvotes: 6

RolandasR
RolandasR

Reputation: 3047

try /mis instead of /iU

Upvotes: 0

Related Questions