Friday, January 15, 2010

URI Validation Using Regular Expression

who know about regular expression?
i need to validate a uri.
so create a validation script using preg_match() on PHP.
but, i get something wrong with my script. can you help me?

this is my uri validation function:
function valid_uri($str){
$patern = "/^((ht|f)tp(s?)\:\/\/|)([a-z0-9]([-.]*[a-z0-9])*(:(0-9)*)*([\/][a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_=]*))?+$/i";
return preg_match($patern,$str);
}

and I have been tested:
$tes=array( "http://www.amikom.ac.id", "amikom.ac.id", "amikom.ac.id.", "ihi amikom.ac.id aha", "https://email.amikom.ac.id","www..com", "http://e-learning.com/", "e-learning.com/index.php", "e-learning.com/index.php?x=1234&a=897", "bukan uri","anang.",".anang.",".com", "http://.com","saya.#@%\$#ini.com");
foreach($tes as $item){
echo "\n".(($this->validasi->valid_uri($item))?"yes":"no")." ".$item;
}


and this is the result:
yes http://www.amikom.ac.id
no amikom.ac.id
no amikom.ac.id.
no ihi amikom.ac.id aha
yes https://email.amikom.ac.id
no www..com
yes http://e-learning.com/
yes e-learning.com/index.php
yes e-learning.com/index.php?x=1234&a=897
no bukan uri
no anang.
no .anang.
no .com
yes http://.com
no saya.#@%$#ini.com


".com" is not valid url, but why "http://.com" is valid?
i just stuck here.
anyone can help me?

No comments:

Post a Comment