如何使用PHP使字符串对href属性安全?

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"