Search code examples
phpregexdomparser

Echo last five divs


How would I use php to echo the last 5 divs?

For example, this string:

<div style='df">cool</div><div>cooletre</div><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div>

How would I do this? With a domparser, regex or what?

Could this be modified to accomplish this? The code here fetches the first five, yet I'd like to fetch the last five.

$string = '<div class="div">1</div><div class="div">2</div><div class="div">3</div><div class="div">4</div><div class="div">5</div><div class="div">end!</div>';

$dom = new DOMDocument();
$new_dom = new DOMDocument;
$dom->loadHTML($string);

$count = 0;
foreach ($dom->getElementsByTagName('div') as $node)
{
    $new_dom->appendChild($new_dom->importNode($node, TRUE));
    if (++$count >= 5)
        break;
}

echo $new_dom->saveHTML();

Solution

  • How about with xpath?

    $xpath = new DOMXPath($dom);
    foreach($xpath->query('//div[position()>last()-5]') as $div){
      echo $dom->saveHTML($div);
    }