Page 1 of 1

regex for URL validation

Posted: Tue Jun 29, 2010 9:44 am
by fael097
hey folks!
i got this regex:

Code: Select all

preg_match("/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i", $url
and its cool for regular urls, but it wont accept a slash at the end, or even slash something, like http://www.example.com/index.php

any clues how to add support to that?
the regex i really wanted is like this:

(http(s):// or ftp://) [here could be letters, numbers, dots, dashes, slashes, etc] dot [here would accept letters only, 2 or 3 digits for endings like com, co, net, it, tk]{i dont know if numbers are needed, i've only seen extensions with 2 or 3 characters, and no numbers, please correct me}[and anything again, like whatever can come after the .com, .co .net, could be anything like extension.php?variable=value]

hope i make myself clear enough!
thanks in advance people

Re: regex for URL validation

Posted: Tue Jun 29, 2010 10:00 am
by AbraCadaver
Why a regex?

Code: Select all

filter_var('http://www.example.com/index.php', FILTER_VALIDATE_URL);

Re: regex for URL validation

Posted: Tue Jun 29, 2010 10:52 am
by fael097
AbraCadaver wrote:Why a regex?

Code: Select all

filter_var('http://www.example.com/index.php', FILTER_VALIDATE_URL);
that is even worse than my regex, it will only require a http:// in front of it, it will validate "http://adsfkjchawuifhw"

Re: regex for URL validation

Posted: Tue Jun 29, 2010 12:48 pm
by AbraCadaver
fael097 wrote:
AbraCadaver wrote:Why a regex?

Code: Select all

filter_var('http://www.example.com/index.php', FILTER_VALIDATE_URL);
that is even worse than my regex, it will only require a http:// in front of it, it will validate "http://adsfkjchawuifhw"
Actually it is "better" for a URL which is what you asked for. A URL must start with a scheme (in this case http://) followed by a hostname (in this case adsfkjchawuifhw). So maybe you don't want to match URLs, but specific types of URLs or partial URLs?