-3

I want to validate URL in PHP but the function should accept the URL even if http:// or https:// not present in the input.

Following URL's should be acceptable:

http://example.com
http://www.example.com
https://example.com
https://www.example.com
www.example.com
example.com

It should not accept ftp protocol, IP address, Port, URL path, query, or fragment.

3
  • 1
    What did you tried ? Commented May 21, 2017 at 6:19
  • If you have a problem you can post what you've tried with a clear explanation of what isn't working and provide a Minimal, Complete, and Verifiable example. I suggest reading How to Ask a good question. Also, be sure to take the tour Commented May 21, 2017 at 6:20
  • Not sure what you're trying to do, but it's almost certain to lead to disaster. What about all the new TLDs? For example, realtor. That's one word, no dots, and is perfectly valid. How do you plan to handle situations like that? Commented May 21, 2017 at 6:22

1 Answer 1

1

Try this regex:

^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$

You should add ? after http(s) and www in order to make them optional.

Demo: https://regex101.com/r/8So1CF/1/

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks it worked well but one thing I missed in acceptable example list is trailing slash. e.g. example.com So I edited your regex by adding (\/)? at last: ^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$
@MahadevMajaladar That's right! Adding (\/)? at the end is the correct way to account for the trailing slash. I edited my answer to reflect that.
What change should I make If I want to accept subdomains also?
replace www with \w+
Thanks. @Ibrahim

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.