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”
