Adam Ramadhan
Adam Ramadhan

Reputation: 22820

subdomain extract without regex with php

is there a great way to extract subdomain with php without regex ?

why without regex ?

there are a lot of topic about this, one if them is Find out subdomain using Regular Expression in PHP

the internet says it consumes memory a lot, if there is any consideration or you think better use regex ( maybe we use a lot of function to get this solution ) please comment below too.

example

static.x.com = 'static'
helloworld.x.com = 'helloworld'
b.static.ak.x.com = 'b.static.ak'
x.com = ''
www.x.com = ''

Thanks for looking in.

Adam Ramadhan

Upvotes: 0

Views: 686

Answers (4)

NikiC
NikiC

Reputation: 101946

function getSubdomain($host) {
    return implode('.', explode('.', $host, -2));
}

explode splits the string on the dot and drops the last two elements. Then implode combines these pieces again using the dot as separator.

Upvotes: 0

Jakob Alexander Eichler
Jakob Alexander Eichler

Reputation: 3056

You can first use parse_url http://www.php.net/manual/de/function.parse-url.php and than explode with . as delimiter on the host http://www.php.net/manual/de/function.explode.php

I would not say it is quicker (just test it), but maybe this solution is better.

Upvotes: 1

Grad van Horck
Grad van Horck

Reputation: 4506

http://php.net/explode ?

Just split them on the dot? And do some functions?

Or if the last part (x.com) is the same everytime, do a substring on the hostname, stripping of the last part.

The only exception you'll have to make in your handling is the www.x.com (which technically is a subdomain).

$hostname = '....';
$baseHost = 'x.com';

$subdomain = substr($hostname, 0, -strlen($baseHost));
if ($subdomain === 'www') {
  $subdomain = '';
}

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318698

Whoever told you that regexes "consume a lot" was an idiot. Simple regexes are not very cpu/memory-consuming.

However, for your purpose a regex is clearly overkill. You can explode() the string and then take as many elements from the array as you need. However, your last example is really bad. www is a perfectly valid subdomain.

Upvotes: 1

Related Questions