Awais Qarni
Awais Qarni

Reputation: 18006

Regular expression to validate url with www but optional http or https

I want to have a regex that will validate url in following way

http://www.google.com   ->valid url
www.google.com          ->valid url
google.com              ->in-valid url
http://google.com       ->in-valid url

I have tried following regex from here

/(?:https?:\/\/)?(?:[a-zA-Z0-9.-]+?\.(?:[a-zA-Z])|\d+\.\d+\.\d+\.\d+)/

but it doens't validate the existence of www

Upvotes: 0

Views: 1285

Answers (3)

user2705585
user2705585

Reputation:

To match www you will have to use regex like this.

Regex: (?:https?:\/\/)?www\.[a-zA-Z0-9.-]+.[a-zA-Z]+|(?:\d\.?){4}

Regex101 Demo

Upvotes: 0

Bohemian
Bohemian

Reputation: 425003

Put www in your regex:

/^(?:https?:\/\/)?(www(\.[\w-]+)+|\d+(\.\d+){3})/

I also improved it a bit (so it doesn't match "www......" etc)

See live demo.

Upvotes: 0

anubhava
anubhava

Reputation: 785108

You can use this regex in PHP:

$re = '~\b(?:https?://)?(www\.[^.\s]+\.[^/\s]+|\d+\.\d+\.\d+\.\d+)~';

RegEx Demo

This regex will enforce www. after optional htpp:// or https:// before it.

Another option in PHP is to use parse_url function and check for result['host'] array entry.

Upvotes: 1

Related Questions