-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.

Mahadev Majaladar
  • 39
  • 1
  • 2
  • 10
  • 1
    What did you tried ? – JazZ May 21 '17 at 06: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](https://stackoverflow.com/help/mcve). I suggest reading [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Also, be sure to take the [tour](https://stackoverflow.com/tour) – Yash Karanke May 21 '17 at 06: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? – Brad May 21 '17 at 06:22

1 Answers1

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/

Ibrahim
  • 6,006
  • 3
  • 39
  • 50