Test a URL with regular expressions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jesse
Forum Newbie
Posts: 1
Joined: Sat Jun 22, 2002 8:05 pm
Contact:

Test a URL with regular expressions

Post 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
will
Forum Contributor
Posts: 120
Joined: Fri Jun 21, 2002 9:38 am
Location: Memphis, TN

Post 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)
&#123;
	// 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
&#125;
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>)
Post Reply