Page 1 of 1

help with url validation

Posted: Mon Jan 28, 2008 12:32 pm
by Chalks
I've spent the better part of an hour trying to find a regex to validate urls. It is going to be used on a personal website that I have the ONLY password to, so I'm not too concerned if it's a little more lenient than it should be. However, I apparently fail at regex. I've been trying this:

Code: Select all

function validLink($link)
{
  $pattern = "!^((http|https)\://)?([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*(localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/[a-zA-Z0-9\./_-]*[a-zA-Z0-9\.\,\?'\\\+&%\$#\=~_\-]*)*/*$!";
  if(preg_match_all($pattern, $l, $junk)!=1)
    return false;
  return true;
}
Doesn't work.

I've tried the following regexs as well:

Code: Select all

^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$
^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$
^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4})(\:[0-9]+)?(/[^/][a-zA-Z0-9\.\,\?\'\\/\+&%\$#\=~_\-@]*)*$
along with several others.


None of them work. I'm starting to think that maybe my code itself is wrong, not the regexs. If you guys could take a look for me, it'd be much appreciated. :)


Edit: part of that hour or so was spent searching this forum as well... and I came across the post astion made with a _huge_ regex for url validation, but... I opted not to try that one.

Re: help with url validation

Posted: Sat Feb 09, 2008 4:32 pm
by GeertDD
Maybe this could help you: http://www.bennadel.com/blog/487-Using- ... Fusion.htm

Or was that the _huge_ regex you were talking about? :roll:

Re: help with url validation

Posted: Sat Feb 09, 2008 4:38 pm
by Benjamin
Chalks wrote:I came across the post astion made with a _huge_ regex for url validation, but... I opted not to try that one.
It works and it's valid :drunk:

Re: help with url validation

Posted: Sat Feb 09, 2008 5:35 pm
by coderdan

Code: Select all

if(@parse_url($link)) 
{
echo 'Valid link';
} 

Re: help with url validation

Posted: Sat Feb 09, 2008 8:22 pm
by Benjamin
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.