0

Possible Duplicate:
PHP: Strip a specific tag from HTML string?

Hi All,

I want to remove li from a string. I'm using following regular 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);
Community
  • 1
  • 1
KutePHP
  • 2,206
  • 6
  • 36
  • 54

2 Answers2

0

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

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Anpher
  • 4,567
  • 24
  • 24
0

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();
Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445