0
0
PhpHow-ToBeginner · 3 min read

How to Validate URL Using Regex in PHP: Simple Guide

To validate a URL in PHP using regex, use the preg_match function with a pattern that matches the URL format. For example, preg_match('/^(https?:\/\/)?([\w\-]+\.)+[\w\-]+(\/\S*)?$/', $url) returns 1 if the URL is valid.
📐

Syntax

The basic syntax to validate a URL using regex in PHP is:

  • preg_match($pattern, $string): Checks if the string matches the regex pattern.
  • $pattern: The regular expression defining the URL format.
  • $string: The URL string to validate.

If the URL matches the pattern, preg_match returns 1 (true), otherwise 0 (false).

php
preg_match('/^(https?:\/\/)?([\w\-]+\.)+[\w\-]+(\/\S*)?$/', $url)
💻

Example

This example shows how to check if a URL is valid using regex in PHP. It prints "Valid URL" if the URL matches the pattern, otherwise "Invalid URL".

php
<?php
$url = "https://www.example.com/path?query=123";
$pattern = '/^(https?:\/\/)?([\w\-]+\.)+[\w\-]+(\/\S*)?$/';

if (preg_match($pattern, $url)) {
    echo "Valid URL";
} else {
    echo "Invalid URL";
}
?>
Output
Valid URL
⚠️

Common Pitfalls

Common mistakes when validating URLs with regex in PHP include:

  • Using too simple patterns that allow invalid URLs.
  • Not escaping special characters like slashes / in the regex.
  • Ignoring URL parts like query strings or ports.
  • Trying to cover all URL cases with one regex, which can get very complex.

For example, this pattern misses query strings and ports:

php
<?php
// Incorrect pattern (misses query strings and ports)
$bad_pattern = '/^https?:\/\/\w+\.\w+$/';
$url = 'https://example.com?query=1';

if (preg_match($bad_pattern, $url)) {
    echo "Valid URL";
} else {
    echo "Invalid URL"; // This will print
}

// Correct pattern includes optional query and path
$good_pattern = '/^(https?:\/\/)?([\w\-]+\.)+[\w\-]+(\/\S*)?$/';
if (preg_match($good_pattern, $url)) {
    echo "\nValid URL"; // This will print
} else {
    echo "\nInvalid URL";
}
?>
Output
Invalid URL Valid URL
📊

Quick Reference

Tips for URL validation with regex in PHP:

  • Use preg_match with a pattern that covers protocol, domain, and optional path/query.
  • Escape special characters like / in regex.
  • Test your regex with various URL examples.
  • Consider using PHP's filter_var with FILTER_VALIDATE_URL for simpler validation.

Key Takeaways

Use preg_match with a proper regex pattern to validate URLs in PHP.
Escape special characters in regex to avoid errors.
Test regex with different URL formats including query strings and ports.
Avoid overly simple patterns that miss valid URL parts.
Consider filter_var for easier URL validation if regex is too complex.