-3

I have the following code:

$url=$_SERVER['HTTP_HOST']; // www.abc.alpha.beta.xyz
$url=strtolower($url);
$rwww=str_replace("www.", "", $url);

But this results in abc.alpha.beta.xyz, the desired result is abc. How can I get just the first subdomain, ignoring www if present?

AD7six
  • 63,116
  • 12
  • 91
  • 123

2 Answers2

0

I think you can use the PHP strpos() function to check if the subdomain URL string contains the word alpha

// Search substring  
$key = 'alpha'; 
$url = 'http://abc.alpha.beta.xyz';

if (strpos($url, $key) !== false) { 
    echo $key; 
}  

Not the best solution but might be helpful for you to get started.

fmsthird
  • 1,745
  • 2
  • 17
  • 34
0

There are a lot of ways to do that, a simple one being:

$host = $_SERVER['HTTP_HOST'] ?? 'www.abc.alpha.beta.xyz';
$parts = explode('.', $host);

$answer = null;
foreach ($parts as $subdomain) {
    if ($subdomain === 'www') {
        continue;
    }
    $answer = $subdomain;
    break;
}

echo "The answer is '$answer'";

Which would output:

The answer is 'abc'

Be aware that this is a very naïve approach and will return example for the input www.example.com - which isn't a subdomain.

AD7six
  • 63,116
  • 12
  • 91
  • 123