URL Validation using Regular Expression

URL Validation using Regular Expression

<?php
$url = ‘http://www.example.org’;

$valid = preg_match(’/^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z0-9-]*)$/i’, $url);
if($valid) {
echo ‘URL is Valid’;
} else {
echo ‘URL is not Valid’;
}

?>

Patten explanation:
——————-

^http(s)?://[a-z0-9-]+(.[a-z0-9-]*)(.[a-z0-9-]*)

patten ^http

1. ^ - should starts with
2. ^https - so now the string should start with http

patten (s)?

4. ?- means patten can have 0 or more match
5 (s)? - Can contains a ’s’ or not

patten ://

6. now matching “://”

patten [a-z0-9-]+

7. Now this part will match somthing like “www”
8. [a-z0-9-]+ it can contain a-z or 0 to 9 and can contain a ‘-’

Stil now we are matched “http://www”

Patten (.[a-z0-9-]+)*
9. Now this part will match a singl dot ‘.’ and the domain name
10. Can contain . or a to z or 0-9 or ‘-’

Stil now we are matched “http://www.example”

11. the next it will match “.org,.com”

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.