-2

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();
user208829
  • 15
  • 7
  • Can you put them in an array? – Ryan B Jan 30 '13 at 21:24
  • 2
    possible duplicate of [PHP echo last 5 divs](http://stackoverflow.com/questions/14612775/php-echo-last-5-divs); the title is better though. Still not much expansion on why copy&pasted code sans attribution that's clearly meant for [extracting the **first** five elements](http://stackoverflow.com/questions/14077304/php-echo-first-divs), or how you think it operates, or what *you tried yourself* to adapt it. SO isn't meant for plzsendtehcodez questions. – mario Jan 30 '13 at 21:28
  • I have no clue about what to adapt. So your saying that any question, asking to be pointed in the right direction, is a "plzsendtehcodez"?? – user208829 Jan 30 '13 at 21:31

2 Answers2

2

A not so smart approach would be to count all opening div tags. Say you get n. Now find the n-5th div tag and from there, find the 5th closing div tag. Everything in between is what you're looking for.

The number of opening div tags can be obtained like that:

$num_div_tags = count(explode('<div', strtolower($string))) - 1;

From there, figuring out the 5th last div tag should be fairly straightforward.

The elegance of this solution perfectly fits the elegance of PHP.


In case you're not satisfied with this solution, you might as well come up with a simple finite state machine that iterates over the string char by char, detects opening and closing div tags, saves each pair in a circular list of length 5 and prints all list elements once the end of the string is reached.

Philip
  • 5,795
  • 3
  • 33
  • 68
0

How about with xpath?

$xpath = new DOMXPath($dom);
foreach($xpath->query('//div[position()>last()-5]') as $div){
  echo $dom->saveHTML($div);
}
pguardiario
  • 53,827
  • 19
  • 119
  • 159