Skip to content
PHP Logo

How can the regular expression pattern be improved to accurately identify URLs that start with "http://www." or "www" in PHP?

To accurately identify URLs that start with "http://www." or "www" in PHP, the regular expression pattern can be improved by using the "|" (OR) operator to match either of the two cases. This way, the pattern will correctly identify URLs that start with either "http://www." or "www".

php
$url = "http://www.example.com";

$pattern = '/^(http:\/\/www\.|www\.)/';
if (preg_match($pattern, $url)) {
    echo "URL matches the pattern";
} else {
    echo "URL does not match the pattern";
}