Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.