开发者

Replace UL tags with specific class

开发者 https://www.devze.com 2023-01-17 23:29 出处:网络
I\'m trying to replace all ul tags with a level0 class, something like this: <ul> <li&g开发者_如何学编程t;Test

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

<ul>
    <li&g开发者_如何学编程t;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


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


try /mis instead of /iU


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号