Skip to content

Instantly share code, notes, and snippets.

@miklb

miklb/link.php

Last active Apr 12, 2017
Embed
What would you like to do?
attempting to get last a tag and apply a class
@miklb

This comment has been minimized.

Copy link
Owner Author

@miklb miklb commented Apr 12, 2017

<blockquote class="twitter-tweet" data-width="500"><p lang="en" dir="ltr">Morning from an alley in Bayonne, New Jersey (home of that guy Rocky was written about) (and… <a href="https://t.co/93FGCm9TcX">https://t.co/93FGCm9TcX</a></p>&mdash; CORY BRANAN (@Corybranan) <a href="https://twitter.com/Corybranan/status/851861980381986816">April 11, 2017</a></blockquote><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

sample $embed_html

@chrisjdavis

This comment has been minimized.

Copy link

@chrisjdavis chrisjdavis commented Apr 12, 2017

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();
@miklb

This comment has been minimized.

Copy link
Owner Author

@miklb miklb commented Apr 12, 2017

Updating the gist to include LIBXML_HTML_NOIMPLIED to the loadHTML so the saveHTML doesn't include the <html><body> tags.

@miklb

This comment has been minimized.

Copy link
Owner Author

@miklb miklb commented Apr 12, 2017

@chrisjdavis works like a charm

@miklb

This comment has been minimized.

Copy link
Owner Author

@miklb miklb commented Apr 12, 2017

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.

@norcross

This comment has been minimized.

Copy link

@norcross norcross commented Apr 12, 2017

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
You can’t perform that action at this time.