HowTo: Extract links from HTML string with PHP

Published on Jul 5, 2021 in Code Snippets

While working on a project I needed to extract links from HTML strings to create jobs for tracking clicks and visits etc. Here’s the function I wrote in PHP to extract the links from HTML strings in PHP.

<?php
public function extractLinks(string $html): array
{
    $links_array = [];
    if (preg_match_all('/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*?)<\/a>/i', $html, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
            array_push($links_array, [$match[1], $match[2]]);
        }
    }

    return $links_array;
}
?>

I hope this helps, if you are looking for such function. Stay tuned for more code snippets and tips

 
previous article

HowTo: Share your local websites with others via the internet.

Published on Jul 5, 2021