Reputation: 18006
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
Reputation:
To match www
you will have to use regex like this.
Regex: (?:https?:\/\/)?www\.[a-zA-Z0-9.-]+.[a-zA-Z]+|(?:\d\.?){4}
Upvotes: 0
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
Reputation: 785108
You can use this regex in PHP:
$re = '~\b(?:https?://)?(www\.[^.\s]+\.[^/\s]+|\d+\.\d+\.\d+\.\d+)~';
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