How to get all links within a post and filter for ones with specific URLs?

Question

Overview

I’m trying to recreate a “link preview” of cited URLs in my articles. For example: my sentence [1]. The 1 in this case points to a site with biomedical publications. I would like to somehow when a user hovers this citation have a tooltip show with the link’s title and meta description.

What I’ve tried

So far, I’ve only found a way to use regex to filter the URL for a specific keyword in it and output the title and description. See below:

<?php

function file_get_contents_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$html = file_get_contents_curl("https://www.ncbi.nlm.nih.gov/pubmed/29693607#");

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');

//get and display what you need:
$title = $nodes->item(0)->nodeValue;

$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
}

echo "<strong>Title</strong>: $title". '<br/>';
echo "<strong>Description</strong>: $description". '<br/>';

?>

This snippets works fine for an individual defined URL but how can I build on this to insert all of the matching URLs and insert the retrieved content into a div inside the anchor tag when a user hovers?

Thanks for the assistance 🙏🏽

0
, , Kevin Rajaram 4 months 0 Answers 57 views 0

Leave an answer