Skip to content

Instantly share code, notes, and snippets.

@hthetiot
Created January 25, 2012 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hthetiot/1675794 to your computer and use it in GitHub Desktop.
Save hthetiot/1675794 to your computer and use it in GitHub Desktop.
function getCommonDomain($domainA, $domainB) {
$domainAParts = explode('.', $domainA);
$domainBParts = explode('.', $domainB);
$domainC = false;
$domainTmp = false;
foreach ($domainBParts as $domainBPart) {
// first loop
if (!$domainTmp) {
$domainTmp = implode('.', $domainBParts);
// last loop on ".com"
} else if (count($domainBParts) == 2) {
break;
// normal loop
} else {
array_shift($domainBParts);
$domainTmp = implode('.', $domainBParts);
}
if (strrpos($domainA, $domainTmp) !== false) {
$domainC = $domainTmp;
break;
}
}
return $domainC;
}
$domainA = 'www.dev.sub1.example.com';
$domainB = 'sub.dev.sub2.example.com';
var_dump(getCommonDomain('www.dev.sub1.example.com', 'sub.dev.sub2.example.com')); // example.com
var_dump(getCommonDomain('www.dev1.sub1.example.com', 'sub.dev.sub1.example.com')); // sub1.example.com
var_dump(getCommonDomain('www.dev.sub1.example.com', 'sub.dev.sub1.example.com')); // dev.sub1.example.com
var_dump(getCommonDomain('www.dev.sub1.example.com', 'sub.dev.sub2.examplex.com')); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment