...

View Full Version : Validating a URL



Ludatha
02-04-2009, 04:56 PM
Hey guys, I am trying to get a perfect regex that validates a url, but I cannot seem to find one.

The best one I have is this:

preg_match("/^(http(s?):\\/\\/|ftp:\\/\\/{1})((\w+\.)+)\w{2,}(\/?)$/i", $_POST['url'])


But it doesnt validate a url like this:

http://forums.digitalpoint.com/showthread.php?t=1215701#post10533297

You cannot have anything after the .com

I need it to support directories:

http://www.ludatha.com/user/

Files:

http://www.ludatha.com/user.php

_GET Variables

http://www.ludatha.com/user.php?id=Adam

Anchors

http://www.ludatha.com/user.php?id=Adam#comments


Can anyone find me or code me one that works ?

Thanks

Lamped
02-04-2009, 06:13 PM
define('NET_URL_REGEX',
'@
(?# Protocol)
([a-z]{1,6}://)
(?# Login)
(?:([^\:]*)(?:\:([^\@]*))?\@)?
(?# Domain)
([a-z0-9][a-z\.\-]*[a-z])
(?# Port)
(\:[0-9]{1,5})?
(?# Path)
(/[a-zA-Z0-9\$\-\_\.\+\!\'\(\|\)\,\;\/\@\&\=\%]* )?
(?# Query)
(\?[a-zA-Z0-9\$\-\_\.\+\!\*\'\(\|\)\,\;\/\?\:\@\&\=\%]*)?
@Sx'
);

function net_split_url($url) {
/* Near perfect uri matching and splitting */
if (preg_match(NET_URL_REGEX,$url,$matches)) {
$details = array(
'protocol' => $matches[1],
'username' => $matches[2],
'password' => $matches[3],
'domain' => $matches[4],
'path' => $matches[5],
'query' => $matches[6]
);
if ($details['query']) {
$query = explode('&',$details['query']);
$details['query'] = array();
foreach($query as $item) {
list($name,$value) = explode('=',$item,2);
$details['query'][urldecode($name)] = urldecode($value);
}
}
return $details;
} else {
return False;
}
}


Some code I wrote once. Seems pretty accurate. Comes with a free url splitting function to demonstrate.

Lamped
02-04-2009, 06:17 PM
Oh, I missed the anchor. Well feel free to add (?:#([a-zA-Z0-9]*))? under match[7] if you like.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum