0

I want to check that user inserted URL is valid or not. I have different cases to allow user to insert URL

1) www.test.com (valid)
2) http://test.com (valid)
3) http://www.test.com (valid)
4) www.test (not valid)

So this way user will able to insert www or http, If user insert only www then pre-append http:// before URL. I found many regex but they strictly check http://.

Thanks in advance.

Rajeev Ranjan
  • 4,883
  • 2
  • 26
  • 41
hemsbhardiya
  • 1,019
  • 11
  • 34

2 Answers2

5

see this link may help you.

<?php
// Variable to check
$url = "http://www.w3schools.com";

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
     echo("$url is a valid URL");
} else {
     echo("$url is not a valid URL");
}
?>
Nikunj Chotaliya
  • 782
  • 7
  • 19
0

I think in point 3. you have an misstake. You have written "wwww"

apart from this, correct regex pattern could be the following:

^(https?:\/\/)?(www\.)?[a-z0-9]+\.[a-z0-9]{2,3}$
Andret
  • 379
  • 4
  • 21
  • There are also domains like `example.info`; `example.name`; `example.berlin` and so on which aren't considered with this regex. – take Jul 30 '15 at 05:31
  • so it will check if http exist or not if not exist then pre-append it. so how it will work? – hemsbhardiya Jul 30 '15 at 05:39
  • question mark sets the previous sign or group optional, it means "http://" or "https://" can exists or not, but if exists, it cannot be different. With group `(www\.)` this same, becouse there is a question mark after it. `^` at start means that in string anything cannot be befor "http" – Andret Jul 30 '15 at 06:08