1

I've come up with the following regular expression to match the valid url.

^(?:(ftp|http|https):\/\/)?(?:[a-zA-Z]+\.){0,1}(?:[a-zA-Z0-9][a-zA-Z0-9-]+){1}(?:\.[a-zA-Z]{2,6})?$

Which matches (ftp|http|https) optional, domain name without .com or anything but also I want to capture everything that come after .com.

The above regex validates http://stackoverflow.com or localhost or google.com but not http://stackoverflow.com/questions/ask

codef0rmer
  • 10,284
  • 9
  • 53
  • 76

1 Answers1

1

To match remaining URI you can add \S* in the end:

^(?:(ftp|http|https):\/\/)?(?:[a-zA-Z]+\.){0,1}(?:[a-zA-Z0-9][a-zA-Z0-9-]+){1}(?:\.[a-zA-Z]{2,6})?(\/|\/\w\S*)?$

But to parse various components of URL it is much better to use built-in parse_url function.

Alternate to validate local urls:

^(?:(ftp|http|https):\/\/)?(?:[a-zA-Z0-9.]+\.){0,1}(?:[a-zA-Z0-9][a-zA-Z0-9-]+){1}(?:\.[a-zA-Z]{2,6})?(\/|\/[\w#!:.?+=&%@!\-\/]*)?$

eg.: 172.18.11.178

Demo: http://regex101.com/r/vV0sB5

codef0rmer
  • 10,284
  • 9
  • 53
  • 76
anubhava
  • 761,203
  • 64
  • 569
  • 643