How do I find the last <div class> in an HTML File with PHP Simple HTML DOM Parser?
According to the documentation for SIMPLE HTML DOM PARSER (under the tab “How to modify HTML Elements”), this code finds the first instance of <div class="hello">
:
$html = str_get_html('<div class="hello">Hello</div><div class="world">World</div>');
$html->find('div[class=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div class="hello">foo</div><div class="world">World</div>
What if I want to insert 'foo' into the last instance of <div class="hello">
, assuming that the HTML code has a lot of instances of <div class="h开发者_如何转开发ello">
.
What should replace the 0
?
Well, since
// Find all anchors, returns a array of element objects
$ret = $html->find('whatever');
returns an array
holding all the <whatever>
elements, you can fetch the last element with PHP's regular array functions, e.g. with end
$last = end($ret);
If SimpleHtmlDom fully implements CSS3 Selectors for querying, you can also modify your query to use
:last-of-type
to only find the last sibling in returned nodelist.
From the manual:
// Find lastest anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', -1);
lastChild property returns the last child object of an element.
EDIT: not JQuery obviously :) See the W3C selector reference instead: http://www.w3.org/TR/css3-selectors/#last-child-pseudo
The original post question was "What should replace the 0?"
Answer: -1
精彩评论