Regular expression for checking website url


Question

I need to check the web address, using regular expression.

if user type url as

  1. www.test.com
  2. http://www.test.com
  3. https://www.test.com

i have a regular expression like

/^(http\:\/\/[a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*\.[a-zA-Z]{2,4}(?:\/[a-zA-Z0-9_]+)*(?:\/[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}(?:\?[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)?)?(?:\&[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)*)$/

but it will only allow the second option only. how can i modify the regular expression so that , it should accept 1st and 3rd option too

1
11
11/28/2011 3:44:53 AM

Accepted Answer

This is a pretty basic expression for testing domain names:

@^(http\:\/\/|https\:\/\/)?([a-z0-9][a-z0-9\-]*\.)+[a-z0-9][a-z0-9\-]*$@i

Should match:

domain.com
www.domain.com
http://domain.com
https://domain.com
22
3/22/2010 6:24:59 AM

Use the following program for validating the website URL.

It will be validating the following and any valid website URL.

  1. www.test.com
  2. http://www.test.com
  3. https://www.test.com

    <?php
            $string_url="https://www.test.com";
            $reg_exp = "/^(http(s?):\/\/)?(www\.)+[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$/";
            if(preg_match($reg_exp, $string_url) == TRUE){
            echo "URL is valid format";
            }
            else{
            echo "URL is invalid format";
            }
    ?>



Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon