How can one ensure that a regular expression for validating URLs allows for optional subdomains in PHP?

To ensure that a regular expression for validating URLs allows for optional subdomains in PHP, you can modify the regex pattern to include the subdomain as an optional group. This can be achieved by enclosing the subdomain part of the pattern in parentheses followed by a question mark to make it optional.

$url = "http://www.example.com";
$pattern = '/^(https?:\/\/)?(www\.)?([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-z]{2,}(\.[a-z]{2,})?$/';

if (preg_match($pattern, $url)) {
    echo "Valid URL";
} else {
    echo "Invalid URL";
}