Reputation: 1125
I want to check a URL to see if it is a Google url or not.
I've got this function
function isValidURL($url)
{
return preg_match('|^http(s)?://google.com|i', $url);
}
If i try
if ( isValidURL('http://google.com/') ){
echo 'yes its google url';
}
It works fine. But if I try
if ( isValidURL('http://www.google.com/') ){
echo 'yes its google url';
}
(with www
) I get an error!
Upvotes: 0
Views: 149
Reputation: 1054
I like to use PHP's parse_url function to analyse url's. It returns an array with each part of the URL. This way you can be sure you're checking the correct part and it won't be thrown by https or query strings.
function isValidUrl($url, $domain_to_check){
$url = parse_url($url);
if (strstr($url['host'], $domain_to_search))
return TRUE;
return FALSE;
}
Usage:
isValidUrl("http://www.google.com/q=google.com", "google.com");
Upvotes: 0
Reputation: 5857
If you're going to support googles subdomains, try:
preg_match('/^https?:\/\/(.+\.)*google\.com(\/.*)?$/is', $url)
Upvotes: 0
Reputation: 10529
Sure, because your regular expression is not ready to handle www.
Try
function isValidURL($url)
{
return preg_match('|^http(s)?://(www\.)?google\.com|i', $url);
}
Upvotes: 4