Search code examples
phpregexurl-validation

regex to check valid url either http or www


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.


Solution

  • 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");
    }
    ?>