I am now having the regular expression that validates "http".. but i need a single one which also validates the url without a protocol specification....
Asked
Active
Viewed 153 times
0
-
http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url – davidtbernal Dec 28 '10 at 00:43
-
Also: [`parse_url`](http://us3.php.net/manual/en/function.parse-url.php) – davidtbernal Dec 28 '10 at 00:45
-
What about `http://www.google.com/` ? – thirtydot Dec 28 '10 at 00:50
-
@thirtydot: Not valid (relevant) according to the question - reality is probably different, of course. – Jonathan Leffler Dec 28 '10 at 00:52
-
1@Jonathan Leffler: Good luck guessing what the *actual* question is :) – thirtydot Dec 28 '10 at 00:55
3 Answers
1
This will do what you want:
(http://|www\.)google\.com
0
Assuming that you really want to do it with a regex (and not by some other, better method), and also assuming that we are dealing strictly with just the two stated variants of Google's domain (and not other plausible variations), then the difference between the two forms is that one starts 'http://' and the other 'www.', so:
(http://|www\.)google\.com
But you might want to ensure that there's an 'end of word' at the end of '.com' so that it does not match http://google.communitycollege.org/
, for instance.

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278
0
I believe it's bad practice to use regex when it isn't required, look into http://www.w3schools.com/PHP/filter_validate_url.asp
It has flags for requiring a host, which I don't believe you're looking for.

Dan LaManna
- 3,431
- 4
- 23
- 35
-
I think VALIDATE_URL is one of the filter_var() functions that's actually implemented as regex. – mario Dec 28 '10 at 01:05
-
@Mario, I meant creating your own regular expression when filter_var functions are available for it. Though I've been looking around and it seems to not be working with just www.url.com, unfortunately. – Dan LaManna Dec 28 '10 at 01:09
-
Yes, it's too stringent, and www.example.com is not a complete URL. Also turns out I'm wrong. It relies upon parse_url(). http://svn.php.net/repository/php/php-src/trunk/ext/filter/filter.c – mario Dec 28 '10 at 01:15