Are there any best practices for handling URL formatting and linking in PHP forums?

When handling URL formatting and linking in PHP forums, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as cross-site scripting attacks. One best practice is to use PHP's built-in filter_var function with the FILTER_VALIDATE_URL filter to validate URLs before displaying or storing them in the database.

// Example of sanitizing and validating a URL input in PHP
$url = filter_var($_POST['url'], FILTER_VALIDATE_URL);
if($url){
   // URL is valid, proceed with storing or displaying
} else {
   // URL is not valid, display an error message to the user
   echo "Invalid URL";
}