简体   繁体   中英

Manipulate and remove a DOM element from parsed HTML

I'm new to both HTML & PHP. I'm attempting to remove multiple DOM elements from a parsed HTML string.

For example:

<tbody>
    <tr>
        <td>I'd like to find and remove this text</td>
        <td>&amp; possibly this too</td>
        <td>can you help?</td>
    </tr>
 </tbody>

Thanks in advance!

DOMDocument is much better for dealing with DOM manipulation ( SimpleXML is good for just parsing):

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$textNodes = $xpath->query('//text()');
foreach ($textNodes as $node) {
   $node->parentNode->removeChild($node);
}

Very simply if I were to remove lots of things from a string in PHP I would create an array of the parts to remove, loop through them and remove them one at a time from the big string.

Like

$html = "Loads of html blah blah blah blah......";

$array = array(
        "Remove me",
        "and me",
        "remove me too"
        );

foreach($array as $string){
    str_replace($string, '', $html);
}

For more information on str_replace see http://php.net/manual/en/function.str-replace.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM