Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip a tag and all of its inner html using the tag's id?

Tags:

I have the following html:

<html>  <body>  bla bla bla bla   <div id="myDiv">           more text       <div id="anotherDiv">            And even more text       </div>   </div>    bla bla bla  </body> </html> 

I want to remove everything starting from <div id="anotherDiv"> until its closing <div>. How do I do that?

like image 653
coderama Avatar asked Jul 22 '10 11:07

coderama


People also ask

How do you remove HTML tags in HTML?

Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.

Which tag is used to remove all HTML tags from a string?

The strip_tags() function strips a string from HTML, XML, and PHP tags.

What does it mean to strip HTML?

stripHtml( html ) Changes the provided HTML string into a plain text string by converting <br> , <p> , and <div> to line breaks, stripping all other tags, and converting escaped characters into their display values.

How do you cut text in HTML?

In order to strip out tags we can use replace() function and can also use . textContent property, . innerText property from HTML DOM. HTML tags are of two types opening tag and closing tag.


2 Answers

With native DOM

$dom = new DOMDocument; $dom->loadHTML($htmlString); $xPath = new DOMXPath($dom); $nodes = $xPath->query('//*[@id="anotherDiv"]'); if($nodes->item(0)) {     $nodes->item(0)->parentNode->removeChild($nodes->item(0)); } echo $dom->saveHTML(); 
like image 55
Gordon Avatar answered Sep 24 '22 03:09

Gordon


You can use preg_replace() like:

$string = preg_replace('/<div id="someid"[^>]+\>/i', "", $string); 
like image 43
Haim Evgi Avatar answered Sep 26 '22 03:09

Haim Evgi