Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove domain extension

Tags:

regex

php

So let's say I have just-a.domain.com,just-a-domain.info,just.a-domain.net how can I remove the extension .com,.net.info ... and I need the resultes in two variables one with the domain name and another one with the extension.

I tried with str_replace but doesn't work, I guess only with regex....

like image 567
Uffo Avatar asked Oct 04 '10 07:10

Uffo


2 Answers

  preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $domain, $matches);

$matches[1] will have the domain and $matches[2] will have the extension

<?php

$domains = array("google.com", "google.in", "google.co.in", "google.info", "analytics.google.com");

foreach($domains as $domain){
  preg_match('/(.*?)((?:\.co)?.[a-z]{2,4})$/i', $domain, $matches);
  print_r($matches);
}
?>

Will produce the output

Array
(
    [0] => google.com
    [1] => google
    [2] => .com
)
Array
(
    [0] => google.in
    [1] => google
    [2] => .in
)
Array
(
    [0] => google.co.in
    [1] => google
    [2] => .co.in
)
Array
(
    [0] => google.info
    [1] => google
    [2] => .info
)
Array
(
    [0] => analytics.google.com
    [1] => analytics.google
    [2] => .com
)
like image 62
Joyce Babu Avatar answered Sep 20 '22 06:09

Joyce Babu


$subject = 'just-a.domain.com';
$result = preg_split('/(?=\.[^.]+$)/', $subject);

This produces the following array

$result[0] == 'just-a.domain';
$result[1] == '.com';
like image 35
splash Avatar answered Sep 20 '22 06:09

splash