我正在尝试用level0类替换所有ul标签,如下所示:
<ul>
<li>Test
<ul class="level0">
...
</ul>
</li>
</ul>
将被处理为
<ul>
<li>Test</li>
</ul>
我试过
$_menu = preg_replace('/<ul class="level0">(.*)<\/ul>/iU', "", $_menu);
但它不起作用,帮忙?
感谢。
叶海亚
答案 0 :(得分:6)
我确信这是重复的,但无论如何,这里是如何使用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
答案 1 :(得分:0)
尝试/ mis而不是/ iU
答案 2 :(得分:0)
您的代码工作正常 - 除非您将$ _menu作为包含除了您正在执行preg_replace之外的字符的字符串传递,尽管事实上它看起来很好。该字符串还包含标签,中断和空格 - 这是RegEx不寻找的。您可以使用以下方法解决此问题:
(例如)
$_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);
答案 3 :(得分:0)
试
$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));