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?
Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
The strip_tags() function strips a string from HTML, XML, and PHP tags.
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.
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.
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();
You can use preg_replace()
like:
$string = preg_replace('/<div id="someid"[^>]+\>/i', "", $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With