Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

php - Remove domain extension

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....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...