Skip to content
PHP Logo

What are some best practices for extracting and displaying links from HTML text in PHP?

When extracting and displaying links from HTML text in PHP, it is important to use a reliable HTML parsing library such as DOMDocument to accurately extract the links. Additionally, regular expressions can be used to filter out and display only the valid URLs from the HTML text. It is also recommended to sanitize the extracted links to prevent any security vulnerabilities.

php
$html = '<a href="https://www.example.com">Example Link</a>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    $url = $link->getAttribute('href');
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        echo '<a href="' . $url . '">' . $link->nodeValue . '</a><br>';
    }
}