Skip to content

Instantly share code, notes, and snippets.

@miklb
Last active April 12, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miklb/2dff5a40a88c8d76e43b9d4e8771429c to your computer and use it in GitHub Desktop.
Save miklb/2dff5a40a88c8d76e43b9d4e8771429c to your computer and use it in GitHub Desktop.
attempting to get last a tag and apply a class
@miklb
Copy link
Author

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
Copy link

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
Copy link
Author

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
Copy link
Author

miklb commented Apr 12, 2017

@chrisjdavis works like a charm

@miklb
Copy link
Author

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
Copy link

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