开发者

regular expression to remove li in php [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

PHP: Strip a specific tag from HTML string?

Hi All,

I want to remove li from a string. I'm using following reg开发者_C百科ular expression, but it is not working. what can be the issue ?

$str = '<div id="navigation" ><div class="menuwrap"><ul><li><a href="#">Home
</a></li><li class="select"><a href="#">About Us</a></li><li><a href="#">Services 
</a></li><li><a href="#">Clients</a></li><li><a href="#">Contact Us</a></li></ul>
</div><div class="submenu"><ul><li><a href="#">Submenu1</a></li><li><a   
href="#">Submenu2</a></li><li><a href="#">Submenu3</a></li>
<li><a href="#">Submenu4</a>
</li></ul></div></div>';

$replacelink = 'Contact Us';  

echo $str = preg_replace('/<li(.*?)>\s*\b<a(.*?)>\s*\b'.$replacelink.'\b\s*<\/a>  
\b\s*<\/li>/i', '', $str);


This should work:

echo preg_replace('/<li><a[^>]*>'.$replacelink.'<\/a><\/li>/s', '', $str);

But please remember there are tools to manipulate DOM and that's not regexp :)


Remove the word boundaries (\b) from your regular expression. At the moment you're looking for any amount of whitespace followed by a word boundary followed by <. There will never be a word boundary between whitespace and <.

Using the solution in the duplicate, you should be able to do this without regex using the :contains() XPath selector:

$dom = new DOMDocument;
$dom->loadHTML($str);
$xPath = new DOMXPath($dom);
$nodes = $xPath->query('//a:contains('.$replacelink.')');
if($nodes->item(0)) {
    $li = $nodes->item(0)->parentNode; 
    $li->parentNode->removeChild($li);
}
$str = $dom->saveHTML();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜