Compare domains in php
I wrote a small script that provided a URL (For example: code.google.com/ajax/123/1235/214) Would tell you that the actual domain is: code.google.com
When this is compared to code.google.com it return true of course, i want it to return true when it is compared to (anything).google.com So, i want it to return true whenever the actual d开发者_高级运维omain is the same regardless of the subdomain, how to do that?
(This is NOT a homework question, it is for a project I am working on so please provide as much help as possible)
(if you need more information to understand the problem, please write a comment and I will provide more information immediately)
A solution might be to use something like parse_url
to extract the host
portion of your URL (that's probably the easiest way to get that information).
Then, you can explode
that host, using '.
' as separator, to get an array that contains the components of the URL (for instance, you'd have array('code', 'google', 'com')
)
And, finally, only compare the last two elements of the array you have for each URL.
That way, you'd compare 'google
' and 'com
' with the informations from the second URL.
I suppose just using a couple of (simpler) string comparisons might work in some cases ; but don't forget cases like 'www.mywebsite.com
' and 'subdomain.website.com
' -- just an example to show that comparing end of domain names is not enough ^^
It could use some error checking but you can do something like this:
<?php
function url_belongs_to_domain($url, $domain){
$url_domain = parse_url($url, PHP_URL_HOST);
return preg_match('/' . preg_quote($domain, '/') . '$/i', $url_domain)==1;
}
var_dump( url_belongs_to_domain('http://code.google.com/ajax/123/1235/214', 'google.com') );
var_dump( url_belongs_to_domain('http://code.google.com/ajax/123/1235/214', 'code.google.com') );
var_dump( url_belongs_to_domain('http://code.google.com/ajax/123/1235/214', 'www.google.com') );
var_dump( url_belongs_to_domain('http://www.google.com/ajax/123/1235/214', 'google.com') );
var_dump( url_belongs_to_domain('http://www.google.com/ajax/123/1235/214', 'code.google.com') );
var_dump( url_belongs_to_domain('http://www.google.com/ajax/123/1235/214', 'www.google.com') );
?>
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
Be aware that accurate detection of top level domains requires checking against a list since it doesn't follow any rule: in www.google.com it is google.com, in www.google.co.uk it is google.co.uk.
精彩评论