What are the best practices for filtering and displaying links in PHP to avoid issues like ignored links or broken formatting?

When displaying links in PHP, it's important to properly filter and sanitize the input to prevent issues like ignored links or broken formatting. One way to achieve this is by using the `filter_var()` function with the `FILTER_VALIDATE_URL` filter to validate the URL before displaying it. Additionally, you can use `htmlspecialchars()` function to escape special characters in the link to prevent any potential XSS attacks.

$link = "https://www.example.com";
if (filter_var($link, FILTER_VALIDATE_URL)) {
    echo '<a href="' . htmlspecialchars($link) . '">Visit Example</a>';
} else {
    echo 'Invalid URL';
}