Preg_match: get last two domain segments from url in one expression

后端 未结 1 1848
一向
一向 2021-01-29 05:19

There is an example on php.net how to get last two domain segments in two steps:

    

        
1条回答
  •  日久生厌
    2021-01-29 06:07

    This piece of code:

    $domain = 'http://www.php.net/index.html';
    $url    = parse_url($domain);
    $tokens = explode('.', $url['host']);
    
    print_r($tokens);
    

    Will give you this data:

    Array
    (
        [0] => www
        [1] => php
        [2] => net
    )
    

    I believe there is no need for regexs as far as it's very hard to properly parse URL with them. From resulting $tokens array you can extract any part of host name easily.

    Update:

    print_r($url);
    

    $url array contains all necessary details:

    Array
    (
        [scheme] => http
        [host] => www.php.net
        [path] => /index.html
    )
    

    0 讨论(0)
提交回复
热议问题