PHP REGEX: Get domain from URL

前端 未结 9 1790
情歌与酒
情歌与酒 2020-12-08 11:05

What I want


I want to get from a URL the domain part so from http://example.com/ -> example.com

相关标签:
9条回答
  • 2020-12-08 11:10

    I think the following regexp might answers your question.

    This diagram explains how it works, or rather why it works :-)

    $regexp = '/.*\/\/([^\/:]+).*/';
    
    // www.stackoverflow.com
    echo preg_replace($regexp, '$1', 'http://www.stackoverflow.com/questions/ask');
    
    // google.de
    echo preg_replace($regexp, '$1', 'http://google.de/?q=hello');
    
    // it works for the other input tests too ;-)
    
    0 讨论(0)
  • 2020-12-08 11:12

    Best way i think:

    preg_match('/(http(|s)):\/\/(.*?)\//si',  'http://www.example.com/page/?bla=123#!@#$%^&*()_+', $output);
    // $output[0] ------------>  https://www.example.com/
    
    0 讨论(0)
  • 2020-12-08 11:13

    I use:

    $domain = parse_url('http://' . str_replace(array('https://', 'http://'), '', $url), PHP_URL_HOST);
    

    Because parse_url doesn't return host key when schema is missing in $url.

    0 讨论(0)
  • 2020-12-08 11:14

    There's no need to use a regex for this. PHP has an inbuilt function to do just this. Use parse_url():

    $domain = parse_url($url, PHP_URL_HOST);
    
    0 讨论(0)
  • 2020-12-08 11:14

    Here's my quick and dirty solution.

    http://([^/]+).*

    I haven't tested it, but it should grab anything between the http:// and the first slash.

    0 讨论(0)
  • 2020-12-08 11:29
    if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) {
      $domain = $matches[1];
    }
    
    0 讨论(0)
提交回复
热议问题