Page 1 of 1
Test a URL with regular expressions
Posted: Sat Jun 22, 2002 8:05 pm
by jesse
Hello everyone, I've been using PHP for just a couple of months, and recently read about using regular expressions to validate user input. I've been trying to implement this into a guestbook that I'm making, but I'm having trouble with a good regular expression to test against a URL. I'd like to be able to accept all kinds of http addresses, including the long crappy freehosting names. If anyone can show me some code, or point me towards a good tutorial, that would be greatly appreciated.
Thanks a lot,
Jesse
Posted: Sat Jun 22, 2002 8:53 pm
by will
these will get you started...
Code: Select all
// check for URL syntax
function urltest($url)
{
if (ereg("^(їa-zA-Z0-9\-\.].)*їa-zA-Z0-9\-]\.їa-zA-Z]+.*$",$url))
return true;
return false;
}
// ensure that URL begins with 'http://' so it
// can be used in <a> tags
function urltest2($url)
{
// note this will only allow for http://
// not https:// ftp:// or any others
if(substr($url,0,7)=='http://')
return $url
else
return 'http://'.$url
}
i'm not 100% sure what characters can be used in file names, i think it depends on the server OS so i left that open.
i use the second function quite a bit to ensure that they prepend their URL with 'http://'.... otherwise you can't throw it into an anchor tag (<a>)