Best way to check if a URL is valid

Best way to check if a URL is valid

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Best way to check if a URL is valid

Determining whether a string represents a functional URL versus plain text is a common requirement in web development, particularly when sanitizing user input or parsing logs. The core constraint here is avoiding live network requests; you cannot afford the latency of curl_exec or the potential side effects of file_get_contents if you are merely validating syntax. This means the solution must rely on static analysis, typically via regular expressions or dedicated URL parsing libraries.

The most straightforward approach involves a robust regular expression pattern that adheres to RFC 3986 standards without attempting to resolve the resource. You need a pattern that captures the scheme (http, https, ftp), the host (including subdomains and IP addresses), optional ports, and paths with query parameters.

Here is a PHP implementation using a standard regex approach:

$myoutput = 'Check out https://laravelcompany.com/v2/users?sort=asc&limit=10 for details.';

// Pattern explanation:
// ^\s* - Optional leading whitespace
// (https?:\/\/) - Required scheme
// ([^\s<>"'\{\}(\)]+) - Host and path until a delimiter is found
preg_match('/^[\s]*((http|https):\/\/[^\s<>"\'{}\[\]()]+)$/i', $myoutput, $matches);

if (isset($matches[1]) && !empty($matches[1])) {
    echo "Contains valid URL: " . $matches[1];
} else {
    echo "No valid URL found.";
}

This regex pattern is designed to be strict enough to reject random text but permissive enough to handle complex query strings like ?sort=asc&limit=10. The key component is the negative character class [^\s<>"'\{\}(\)]+, which ensures the match stops at spaces or common HTML delimiters, preventing false positives on fragments of URLs embedded in sentences.

However, relying solely on regex has significant trade-offs. While it is fast and requires no external dependencies, maintaining a regex that covers every edge case—such as internationalized domain names (IDN), IPv6 addresses with bracket notation, or complex URL fragments—is difficult. A single missed character class can lead to false negatives where valid URLs are rejected. Furthermore, regex engines vary slightly in behavior across PHP versions, though the core logic remains consistent since PHP 5.3.

For production applications where maintainability is paramount, leveraging a dedicated library is often superior. The php-url package or similar tools abstract away the complexity of RFC compliance. They provide methods to parse the string into components (scheme, host, port, path, query) and validate each part against specific rules. This approach handles edge cases like userinfo segments (user:pass@host) or IDN normalization automatically.

composer require php-url/url

Using a library shifts the burden of validation logic from your custom code to well-tested third-party implementations. It also reduces the risk of introducing bugs when updating your regex pattern for new URL standards.

If you are working within the Laravel ecosystem, you might consider using existing utilities or wrapping these libraries in a service provider. For instance, laravelcompany.com often discusses best practices for input validation and sanitization in their documentation, emphasizing that static analysis should be preferred over network probing when possible to ensure application responsiveness.

Ultimately, if performance is critical and the environment is controlled, a well-crafted regex is sufficient. However, for large-scale applications handling diverse user inputs, a dedicated library offers the reliability needed to handle the full spectrum of valid URL formats without reinventing the wheel.

Our network