DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

URL validation with preg_match() in PHP: define “valid” first

preg_match() can enforce a URL pattern you define, but it is not a universal URL or safety validator. Define the accepted form, match the downstream client, and apply separate scheme, host, and fetch policies.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

preg_match() can check whether a string matches a URL pattern you write. A successful match does not prove that the URL conforms to every URI standard, uses an approved scheme, resolves to a real host, is safe to fetch, or will be accepted by another client. Start by defining the application’s contract: an absolute HTTP(S) URL, any URI with a scheme, a relative reference, or a destination a particular client can actually use.

What preg_match() actually validates

preg_match() tests text against one regular expression. It validates only the grammar represented by that expression, not “URLs” in the abstract. A pattern for an internal web form might require https:// and a hostname; a router may need to accept relative references such as /docs/start; another application may accept any URI scheme.

Keep the pattern tied to a clearly stated contract. Do not describe a short regex as a complete, standards-compliant URI parser.

A deliberately narrow HTTP(S) check

This example requires an absolute HTTP or HTTPS URL, a DNS-style ASCII hostname, an optional port, and an optional path, query, or fragment:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$pattern = '~^https?://(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?.)+[A-Za-z]{2,63}(?::[0-9]{1,5})?(?:[/?#][^s]*)?$~i';

$isHttpUrl = preg_match($pattern, $value) === 1;

This is an application policy, not a universal URL definition. It excludes IP-literal hosts, internationalized domain names, localhost-style names, credentials, and many legal URI forms. Add or remove those cases only when the consuming application explicitly needs them, and test the result against that application.

Relative references need a different contract

If links such as /account, ../images/logo.svg, or ?page=2 are valid inputs, an absolute-URL pattern will reject them by design. Use a separate relative-reference grammar or parse and resolve the reference against a known base URL. Do not silently prepend a scheme merely to make a string pass a check.

Choosing between a regex and PHP URL functions

Approach What it is useful for Important limits
preg_match() Enforcing a small, explicit input contract such as “HTTPS links only.” Coverage is limited to the pattern; maintenance and edge cases are your responsibility.
filter_var($value, FILTER_VALIDATE_URL) A built-in format check when its accepted grammar matches your application. The PHP Manual describes it as based on RFC 2396, which it calls obsolete. Schemes are permissive, unexpected schemes can pass, and the filter is ASCII-only.
parse_url() Breaking a URL-like string into components for application-specific checks. Parsing components is not the same as proving that the complete input is valid for your policy; its documented grammar basis differs from the validation filter.
A newer URI parser or downstream client Matching the grammar and behavior of the library that will actually consume the value. Verify behavior on the PHP version and client you deploy, including relative references and internationalized domains.

The PHP documentation says FILTER_VALIDATE_URL follows RFC 2396, while parse_url() uses RFC 3986. RFC 3986 is the IETF generic URI syntax standard published in January 2005. These different bases are one reason two APIs can disagree.

Using FILTER_VALIDATE_URL without overtrusting it

$validFormat = filter_var($value, FILTER_VALIDATE_URL) !== false;

That call is a format result only. PHP documents that the filter works only on ASCII URLs, so internationalized domain names are rejected in their Unicode form. A documented PHP issue also records rejection of scheme-relative references such as //example.com/path. Decide explicitly whether those forms are allowed before choosing this filter.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The manual also warns that schemes are not fully restricted by this check: unusual schemes may be accepted, and examples include loopback addresses. If your application expects web links, check the scheme yourself:

$parts = parse_url($value);

$isWebLink = filter_var($value, FILTER_VALIDATE_URL) !== false
    && is_array($parts)
    && isset($parts['scheme'])
    && in_array(strtolower($parts['scheme']), ['http', 'https'], true);

That still does not establish that the host is reachable, trustworthy, or safe to contact.

Validate for the software that consumes the URL

Interoperability is part of correctness. PHP’s URL-parsing discussion notes that strings accepted by FILTER_VALIDATE_URL may not be accepted by cURL, whose parsing is based on RFC 3986. If the value will be handed to cURL, an HTTP client, a browser, or another parser, test the forms that consumer accepts and use the same assumptions in your validation.

  • Require the schemes the client is intended to handle.
  • Define whether absolute URLs, relative references, ports, credentials, fragments, and IP literals are permitted.
  • Decide how Unicode hostnames are represented and converted, if they are supported.
  • Reject malformed or ambiguous input before passing it to the consumer.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Syntax is not destination safety

Neither a regex match nor FILTER_VALIDATE_URL proves that a destination is safe to fetch. A server-side fetch feature needs a separate policy for allowed schemes, hosts, ports, DNS results, private or loopback address ranges, redirects, and authentication. Re-check the destination after redirects and apply network controls appropriate to the deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a simple link field, a narrow HTTPS pattern may be enough to enforce presentation rules. For an outbound request, treat syntax validation as only the first gate.

A practical decision checklist

  1. Write the accepted forms in plain language: for example, “absolute HTTPS URLs with DNS hostnames,” or “relative paths under this site.”
  2. Choose the parser or regex that represents that contract and the downstream client’s grammar.
  3. Apply explicit scheme, host, port, and character rules instead of assuming a generic validator is an allowlist.
  4. Test boundary cases: relative references, unusual schemes, loopback hosts, Unicode domains, ports, fragments, whitespace, and malformed authority components.
  5. Keep destination authorization and network-safety checks separate from syntax validation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.