What are some best practices for handling URL encoding and HTML validation when manipulating links in PHP?

When manipulating links in PHP, it is important to properly handle URL encoding to ensure that special characters are correctly represented in the URL. Additionally, HTML validation should be performed to prevent any potential security vulnerabilities such as cross-site scripting attacks.

// Example code snippet for handling URL encoding and HTML validation in PHP

$url = "https://example.com/page?param1=" . urlencode($param1);

// HTML validation using htmlspecialchars to prevent XSS attacks
$param2 = "<script>alert('XSS attack!')</script>";
$safe_param2 = htmlspecialchars($param2, ENT_QUOTES, 'UTF-8');

echo "<a href='$url&param2=$safe_param2'>Link</a>";