How about with xpath?
$xpath = new DOMXPath($dom);
foreach($xpath->query('//div[position()>last()-5]') as $div){
echo $dom->saveHTML($div);
}
题
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();
解决方案 2
How about with xpath?
$xpath = new DOMXPath($dom);
foreach($xpath->query('//div[position()>last()-5]') as $div){
echo $dom->saveHTML($div);
}
其他提示
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.