HowTo: Extract links from HTML string with PHP

H

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

About the author

Mohit Aneja

Add Comment

Mohit Aneja

Sharing Best Practices

I love to share the knowledge and experience with like minded people. Feel free to connect with me via any preferred channel.