6

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.

Kevin
  • 41,694
  • 12
  • 53
  • 70
Elton Jamie
  • 586
  • 6
  • 17

1 Answers1

1

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;
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • @EltonJamie yeah just continue to get those after the flag has started, once the ending is found, then `break` it – Kevin Apr 22 '15 at 13:31