MyBB Community Forums

Full Version: URL regex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I'm making a URL shortner, what's a good regex for a URL?
I guess this would be the answer:

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
(2011-05-12, 07:03 PM)Darth Stabro Wrote: [ -> ]I guess this would be the answer:

There is only one passing all the test so, yes Toungue
Hm... it's not working.
Warning: preg_match() [function.preg-match]: Unknown modifier '_'
Just create a little test, and it's working here:
<?php
$url = "http://www.google.com/";
$regex = '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS';

if(preg_match($regex, $url))
{
	echo "passed";
}
else
{
	echo "failed";
}

Didn't use PHP tags to prevent the page from expanding.
Just use base36, that's what TinyURL does. http://en.wikipedia.org/wiki/Base_36

<?php
// Convert base36 code to standard base10 row ID
$id = base_convert($_GET['id'], 36, 10);

// Select row
mysql_query('SELECT xx,yy,zz FROM abcde WHERE id = '.$id);

// Redirect URL
header('Location: xxxxxxxxxxxx');
?>

EDIT: Nvm, it would appear I misunderstood the question.
And what's a regex for upper and lowercase letters, dashes, and numbers?
Consider making use of PHP's parse_url() function instead of using some hard to understand regex.

(2011-05-12, 09:41 PM)Darth Stabro Wrote: [ -> ]And what's a regex for upper and lowercase letters, dashes, and numbers?

[A-Za-z0-9\-]
Pages: 1 2