I’ve found a validation for websites. But later I needed to make some changes and to add special Social Networks (facebook, twitter, plus.google) validation.
This is what I’ve got:
function isValidUrl($url,$media) {
$url= strtolower($url);
// Scheme
$urlregex = "^(https?)\:\/\/";
// User and Pass (optional)
if (!isset($media)) {
$urlregex .= "([A-Za-z0-9+!*(),;?&=\$_.-]+(\:[A-Za-z0-9+!*(),;?&=\$_.-]+)?@)?";
}
// Hostname
if (isset($media)) {
if ($media == 'fb') { $urlregex .= "([facebook]+\.)"; }
else if ($media == 'gplus') { $urlregex .= "([plus\.google]+\.)"; }
else if ($media == 'twitter') { $urlregex .= "([twitter]+\.)"; }
} else {
$urlregex .= "([A-Za-z0-9+\$_-]+\.)";
}
$urlregex .= "*(?:[A-Za-z]{2}|com";
if (!isset($media)) {
$urlregex .= "|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum|cat|coop|int|pro|tel|travel|xxx";
}
// Hostname End
$urlregex .= ")";
// Port/Path (optional)
$urlregex .= "(\:[0-9]{2,5})?";
$urlregex .= "(\/([A-Za-z0-9+\$_-]\.?)+)*\/?";
// Query
$urlregex .= "(\?[A-Za-z+&\$_.-][A-Za-z0-9;:@/&%=+\$_.-]*)?";
// Anchor
$urlregex .= "(#[A-Za-z_.-][A-Za-z0-9+\$_.-]*)?\$^";
return preg_match($urlregex,$url);
}
Simple website is validating alright, but Social Network isn’t in the way I want.
For example http://facebook.com is valid, but I need to be valid an URL like http://facebook.com/something, and to make the first one to become unvalid (same for http://twitter.com and http://plus.google.com). The http://plus.google.com validation doesn’t work, it allows http://plusgoogle.com and other fusions.
What I’d like to change/add:
1) Fix Social Networks (facebook, gplus, twitter) validation as described above;
2) To also allow URLs without protocols http:// or with them and www. both, so to make the link http://stackoverflow.com to become allowed in the ways http://www.stackoverflow.com, stackoverflow.com and www.stackoverflow.com.
EDIT: To make things clear, I call this function the way below.
$error = false;
// For simple URL
$url = $_POST['url'];
if (!isValidURL($url,NULL)) { $error = true; }
// For Facebook URL
$fbpage = $_POST['fbpage'];
if (!isValidURL($fbpage,'fb')) { $error = true; }
// For Twitter URL
$twitterpage = $_POST['twitterpage'];
if (!isValidURL($twitterpage,'twitter')) { $error = true; }
// For Google Plus URL
$gpluspage = $_POST['gpluspage'];
if (!isValidURL($gpluspage,'gplus')) { $error = true; }
I’d do away with the super complex regexen and use already built-in functions:
This is not exhaustive, but I hope you get the idea. See
parse_urlfor more details.