1
votes

As far as i know there are many other questions similar to title, but my main reason for asking this question is i want my validation as perfect as i want. Here is my explanation which URL should valid

http:// (if given then match otherwise skip), domain.com (should match & return validate) subdomain.domain.com (should match & return validate) www.com (should return false) http://www.com (should return false)

I searched a lot about perfect regex pattern according to my need but didn't succeed so thats why i made my self and posting here to want to know that anyother Valid URL would it skip or not except http://localhost. If yes then please correct me.

Pattern:

((?:http|https|ftp)://)?(?:www.)?((?!www)[A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?/?

1
http:// is optional in above regex - Mr.Shan0
I am not sure exactly what you are trying to match or not match that is different from most commonly available URL-matching expressions -- www.com and http://www.com are perfectly valid URLs and each go to a live website. Did you want to match http://localhost; do you want to match IP addresses? -- If you tell us what you are using this for, it may be very helpful. - Code Jockey

1 Answers

1
votes

I know this actually doesn't answer your question directly, but REGEXes aside, you can also use filter_var(), with the flag FILTER_VALIDATE_URL, which returns the URL in case of valid url, or FALSE otherwise:

   var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL));
   // string(18) http://example.com

You can read here the filters used by this function, especially the last row regarding flags used by the VALIDATE_URL filter.

I actually don't know how it's implemented internally, but I suppose it works better than many regexes you can find outside in the wild internet.