How to remove entire div with preg_replace

前端 未结 4 1361
心在旅途
心在旅途 2021-01-16 17:06

Ok, as it is WordPress problem and it sadly goes a little deeper, I need to remove each representation of parent div and its inside:

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 17:27

    I wouldn't use a regular expression. Instead, I would use the DOMDocument class. Just find all of the div elements with that class, and remove them from their parent(s):

    $html = "

    Hello World

    Bar
    "; $dom = new DOMDocument; $dom->loadHTML( $html ); $xpath = new DOMXPath( $dom ); $pDivs = $xpath->query(".//div[@class='sometestclass']"); foreach ( $pDivs as $div ) { $div->parentNode->removeChild( $div ); } echo preg_replace( "/.*(.*)<\/body>.*/s", "$1", $dom->saveHTML() );

    Which results in:

    Hello World

提交回复
热议问题