Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get html between comments block Simple HTM DOM

How can I take a block of DOM by identify its 'comment' tag, like

<!-- start block -->
<p>Hello world etc</p>
<div>something</div>
<!-- end of block -->

I'm using Simple PHP DOM parser, but the doc is incomplete, http://simplehtmldom.sourceforge.net/manual.htm. It's fine if I can do it with pure PHP.

like image 715
Elton Jamie Avatar asked Apr 22 '15 13:04

Elton Jamie


1 Answers

You can try to iterate thru the elements first, then if you found the starting comment, skip it first, then add a flag which starts the concatenation of the next elements. If you reach the end-point, stop the concatenation:

$html_string = '<!-- start block -->
<p>Hello world etc</p>
<div>something</div>
<div>something2</div>
<!-- end of block -->
<div>something3</div>
';

$html = str_get_html($html_string);
// start point
$start = $html->find('*');
$output = ''; $go = false;
foreach($start as $e) {

    if($e->innertext === '<!-- start block -->') {
        $go = true;
        continue;
    } elseif($e->innertext === '<!-- end of block -->') {
        break;
    }

    if($go) {
        $output .= $e;
    }   
}

echo $output;
like image 75
Kevin Avatar answered Oct 24 '22 02:10

Kevin