Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

regex - how to get URL host using php

I would like to get the host name of any url for example if i've the following url

$url = "http://www.google.com";

then i want to get only google what is after dot . and before extension dot . so that it can be applied for all types of urls.

so the results should be google ! i think this might needs regex or somehow any idea how to do it , Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can try

echo __extractName("http://google.com"); 
echo __extractName("http://office1.dept1.google.com");
echo __extractName("http://google.co.uk");


function __extractName($url)
{
  $domain = parse_url($url , PHP_URL_HOST);
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9-]{1,63}.[a-z.]{2,6})$/i', $domain, $list)) {
    return substr($list['domain'], 0,strpos($list['domain'], "."));
  }
  return false;
}

Output

google
google 
google 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...