5

If $domain = apple.com, or mit.org.edu.au, how can I remove the '.com' and everything starting from the dot using PHP? e.g. apple.com becomes apple, mit.org.edu.au becomes mit (disregard www.).

3
  • 3
    What have you tried? See the FAQ, please. Commented Jan 4, 2013 at 3:28
  • can this happen?? @JohnConde Commented Jan 4, 2013 at 3:31
  • @PranavKapoor Not quite, OP is asking for the first token, dup is asking for everything but the last. Commented Jan 4, 2013 at 3:38

6 Answers 6

9

If you already have the domain then simply explode the domain and take the first element of the array.

$domain = 'apple.com';
$domain_parts = explode('.', $domain);
echo $domain_parts[0]; // returns apple

Note that the above will not account for subdomains. I.e. 'www.apple.com' would return 'www'. But based on what you have asked above, explode may be adequate.

If you don't already have the domain then you can use PHP's parse_url function to extract the domain (host) from the URL.

Sign up to request clarification or add additional context in comments.

Comments

2
<?php
$domain1 = 'apple.com';
$domain2 = 'mit.org.edu.au';
$exploded1 = explode('.',$domain1);
$exploded2 = explode('.',$domain2);
echo $exploded1[0];
echo $exploded2[0];
?>

See PHP's explode function. Here's a codepad example.

Comments

1

Use explode.

$tokens = explode(".", "apple.com");
echo $tokens[0]; // apple

Comments

1

It's a simple one line answer:

<?php echo explode('.', $url)[0]; ?>

Comments

1

Like others said, use explode. $raw = 'apple.com'; $url = explode('.',$raw); echo $url[0];

If there is a "www" in the domain, then do a simple check like if($url[0] == 'www'){ echo $url[1]; }else{ echo $url[0]; }

1 Comment

Sorry I don't know how to make it appear in the code box, I am new to SO.
0

I dislike all of these answers... if you KNOW the domain, none of this is necessary... if you DONT KNOW the domain, you most certainly should account for subdomains.

$parts = explode('.', $domain);

array_pop($parts); //remove the TLD

$url = join('.', $parts);  //put it back together, sans the TLD

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.