What are the best practices for parsing and checking for new URLs in PHP?

When parsing and checking for new URLs in PHP, it is important to ensure that the URL is properly formatted and valid. One way to do this is by using the filter_var() function with the FILTER_VALIDATE_URL flag. Additionally, you can use functions like parse_url() to extract different components of the URL for further validation.

$url = "https://www.example.com";

// Check if the URL is valid
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // Parse the URL to extract its components
    $url_components = parse_url($url);

    // Check if the URL has a valid scheme and host
    if (isset($url_components['scheme']) && isset($url_components['host'])) {
        // URL is valid
        echo "URL is valid: " . $url;
    } else {
        // URL is invalid
        echo "Invalid URL";
    }
} else {
    // URL is invalid
    echo "Invalid URL";
}