What are some best practices for defining and outputting URLs as links in PHP?

When defining and outputting URLs as links in PHP, it is important to properly sanitize and validate the URL to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. One common best practice is to use the `htmlspecialchars()` function to escape special characters in the URL before outputting it as a link. Additionally, it is recommended to use the `filter_var()` function with the `FILTER_VALIDATE_URL` filter to validate the URL format.

$url = "https://example.com/page";
$sanitized_url = htmlspecialchars($url);
if (filter_var($sanitized_url, FILTER_VALIDATE_URL)) {
    echo '<a href="' . $sanitized_url . '">Link</a>';
} else {
    echo 'Invalid URL';
}