PDA

View Full Version : validate URL


david07
02-01-2008, 09:04 AM
I hate string validation
can someone please tell me why the following will only let user enter

www.blablabla.com AND NOT www.blabla.com/other which i need.
(it needs not contain http://)

function valid_url($form_vars)
{
if(!preg_match ("/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i", $form_vars))
return true;
else
return false;
}

THANK YOU!.

Fou-Lu
02-01-2008, 05:31 PM
"/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i"
Start with any letter or number, followed by one or more letters, numbers, or hyphens, finishing with a letter or number, and ending with at least one .{2-4}characters.
The check doesn't take into account the possibility for directories, simply because it is ending with the url check, and not continuing. I'm thinking you can actually just get away with removing the $ from the end, you may need to force it be become ungreedy, but methinks that will solve the problem.
Otherwise, simply add in the possibility for directories, something like:

(\/[^\s]*)*(\.[a-z]{2,6})?

Is that right... starting with / followed by any number of characters not starting with a space, all any number of times followed by the possibility of a 2-6 character extension. That looks right, but I haven't tested it.
In either case, you get the idea, the problem is because you are not making a check for anything other than the url in the block, it is bound between the beginning of the string and the end of the string.
Hope that helps!

oesxyl
02-01-2008, 07:30 PM
my version:


$mybase = preg_replace("/^[^:]+:\/\/([^\/]+)/","$1",$url);


but IMO is better to avoid improvisation and if you expect to get a url use parse_url:

http://www.php.net/manual/en/function.parse-url.php

best regards