Would encoding quotation marks and removing eventual javascript: prefixes be enough?
P.S. Safe enough to defeat XSS attacks that is.
you can use the php function to validate urls
$url = "http://google.com";
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
Encoding with htmlspecialchars() with the ENT_QUOTES flag will technically make the URL safe/sanitary for use from an HTML perspective, but it does not guarantee that it'll create a valid address.
$url = 'http://invalid"url';
$url = htmlspecialchars($url, ENT_QUOTES); // Yields "http://invalid"url"
htmlspecialchars() makes the URI safe for using it in an HTML attribute. It guarantees valid HTML, but it does not help anything in regards of security (=the OP wants to protect the users from being presented with malicious JavaScript links).
javascript:is not enough to prevent XSS in a href attribute. Instead I highly recommend you do some whitelisting here (that is far easier to implement and you don't need to be a super-pro to make this safe)