Last active
April 12, 2017 16:25
-
-
Save miklb/2dff5a40a88c8d76e43b9d4e8771429c to your computer and use it in GitHub Desktop.
attempting to get last a tag and apply a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$dom = new DOMDocument; | |
$dom->loadHTML($embed_html, LIBXML_HTML_NOIMPLIED); | |
$nodelinks = $dom->getElementsByTagName('a'); | |
$links = iterator_to_array($nodelinks); | |
var_dump($links); | |
foreach ( $links as $link ) { | |
if (end($links)) { | |
$link->setAttribute("class","u-url"); | |
} | |
}; | |
$embed_html = $dom->saveHTML(); |
This is what I was advocating. Ugly, but seems to work.
$dom = new DOMDocument;
$dom->loadHTML( $embed_html );
$nodelinks = $dom->getElementsByTagName('a');
$links = iterator_to_array($nodelinks);
$count = count( $links );
$i = 0;
foreach ( $links as $link ) $i++; {
if( $i == $count ) {
$link->setAttribute("class", "u-url");
}
};
$embed_html = $dom->saveHTML();
Updating the gist to include LIBXML_HTML_NOIMPLIED
to the loadHTML so the saveHTML doesn't include the <html><body>
tags.
@chrisjdavis works like a charm
To re-iterate my comment on Twitter, this isn't mission critical work, just an itch I wanted to scratch, but at some point would like to understand why the if (end($links))
didn't work.
give this a try:
// Set my DOM.
$dom = new DOMDocument;
$dom->loadHTML( $embed_html );
// Set my XPath lookup.
$xpath = new DOMXPath( $dom );
$links = $xpath->evaluate( '//a' );
// Bail if I don't have any links.
if ( empty( $links->length ) || absint( $links->length ) < 1 ) {
return;
}
// Get the count of my last link.
$last = absint( $links->length ) - 1;
// Set my last item.
$item = $links->item( $last );
// Set the class on my last item.
$item->setAttribute( 'class', 'u-url' );
// Save the HTML back to the DOM.
$html = $dom->saveHTML();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sample $embed_html