2 ways to get a domain name in a URL in PHP

Source: Internet
Author: User
Method 1:

Custom function, the benefit is can be rewritten at any time, insufficient is some domain name may not parse out

function Get_domain ($url) {$pattern = "/[/w-]+/. Com|net|org|gov|biz|com.tw|com.hk|com.ru|net.tw|net.hk|net.ru|info|cn|com.cn|net.cn|org.cn|gov.cn|mobi|name|sh |ac|la|travel|tm|us|cc|tv|jobs|asia|hn|lc|hk|bz|com.hk|ws|tel|io|tw|ac.cn|bj.cn|sh.cn|tj.cn|cq.cn|he.cn|sx.cn| nm.cn|ln.cn|jl.cn|hl.cn|js.cn|zj.cn|ah.cn|fj.cn|jx.cn|sd.cn|ha.cn|hb.cn|hn.cn|gd.cn|gx.cn|hi.cn|sc.cn|gz.cn| yn.cn|xz.cn|sn.cn|gs.cn|qh.cn|nx.cn|xj.cn|tw.cn|hk.cn|mo.cn|org.hk|is|edu|mil|au|jp|int|kr|de|vc|ag|in|me| EDU.CN|CO.KR|GD|VG|CO.UK|BE|SG|IT|RO|COM.MO) (/. ( CN|HK) */";p Reg_match ($pattern, $url, $matches); if (count ($matches) > 0) {return $matches [0];} else{$rs = Parse_url ($url), $main _url = $rs ["Host"];if (!STRCMP (Long2ip (sprintf ("%u", Ip2long ($main _url)), $main _url) {return $main _url;} else{$arr = Explode (".", $main _url), $count =count ($arr), $ENDARR = Array ("com", "net", "org"),//com.cn net.cn, etc. if (in_ Array ($arr [$count-2], $ENDARR)) {$domain = $arr [$count-3]. ".". $arr [$count-2]. ".". $arr [$count-1];} else{$domain = $arr [$count-2]. ".". $arr [$count-1];} return $domain;}}}

Method 2:

With its own function, the advantage is that it's easy to use, and that's what I'm using now.

If you don't want www, you can replace it with Str_replace.

$URL = ' http://www.scutephp.com/index.html '; $tempu =parse_url ($Url) $message = $tempu [' Host '];echo $message;//Output is Www.scutephp.com
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.