Php 从完整URL获取域名

Php 从完整URL获取域名,php,hyperlink,parse-url,Php,Hyperlink,Parse Url,我有一个txt文件(links.txt),里面有数千个链接 我想使用以下代码对所有链接进行排序 <?php function get_domain($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path']; if (preg_match('/(?P<domain>[a

我有一个txt文件(links.txt),里面有数千个链接

我想使用以下代码对所有链接进行排序

<?php
    function get_domain($url)
    {
        $pieces = parse_url($url);
        $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
        if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
            return $regs['domain'];
        }
            return false;
        }
        print get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'
?>
之后:

example.com
example.net
example.org
example.co
example.co.uk

理论上,这很简单:

$file = file('domains.txt');
for ($x=0;$x<count($file);$x++) {
    $file[$x] = get_domain($file[$x]);
}
sort($file);
file_put_contents('domains.txt', $file);
$file=file('domains.txt');

为了($x=0;$XY您可以将每个链接保存到数据库,然后创建一个脚本来检索所有已排序的链接。
文件
,循环生成的数组,对每个数组元素执行所需的操作,使用
文件内容
@CBroe您能给我看一个代码示例吗?@CBroe刚刚看到我的答案完全按照你的建议去做。不确定这里的礼仪/标准,但如果你添加一个答案,我很乐意删除我自己的!@LeonardChallis不用担心,一切都好。(我的只是一个评论。)
$file = file('domains.txt');
for ($x=0;$x<count($file);$x++) {
    $file[$x] = get_domain($file[$x]);
}
sort($file);
file_put_contents('domains.txt', $file);