【问题标题】:Remove URL tail and leave only domain删除 URL 尾部并仅保留域
【发布时间】:2019-11-02 09:16:44
【问题描述】:

我有一个要向其发送链接列表的脚本。如何删除 url tail 并仅保留域?例如:只留下 google.com,而不是 google.com/adwords。

<form method='post'>
<textarea name="url1" cols="40" rows="5"></textarea><br>
<input name="Submit" type='submit' value='Send'>
</form>

<?php
$array = explode("\r\n", $_POST['url1']);
$word_count = (array_count_values($array));
arsort($word_count);
foreach ($word_count as $key=>$val) {
echo '<a href="' . $key . '">' . $key . '</a> - ' . $val . '<br/>'; 
}
?>

我尝试了类似的方法:

$string = array('https://google.com/ytrewq', 'https://google.com/qwerty'); 
$pattern = '/[^/]+$/';
$replacement = "replacement";
print_r (preg_replace($pattern, $replacement, $string));
print_r (preg_grep($pattern, $string));
print_r (preg_filter($pattern, $replacement, $string)); 
print_r (preg_match($pattern,$string,$found));

但它不起作用。

【问题讨论】:

    标签: php arrays regex


    【解决方案1】:
    // for a single URL:
    function getBaseUrl( $url, $includeScheme = false )
    {
        $host = parse_url( $url, PHP_URL_HOST );
        if ( !$includeScheme ) {
            return $host;
        }
    
        $scheme = parse_url( $url, PHP_URL_SCHEME );
        return sprintf( '%s://%s', $scheme, $host );
    }
    
    $url = 'https://google.com/adwords';
    echo getBaseUrl( $url ); // prints 'google.com'
    echo getBaseUrl( $url, true ); // prints 'https://google.com'
    
    // for an array of URLs:
    function getBaseUrls( $urls, $includeScheme = false )
    {
        $baseUrls = [];
        foreach ( $urls as $url ) {
            $baseUrls[] = getBaseUrl( $url, $includeScheme );
        }
    
        return $baseUrls;
    }
    
    $urls = [
        'https://google.com/ytrewq', 
        'https://google.com/qwerty'
    ];
    print_r( getBaseUrls( $urls, true ) );
    

    更多信息请参见https://www.php.net/manual/en/function.parse-url.php

    【讨论】:

    • 它不适用于我的代码中的数组。还是需要对数组使用“foreach”?
    • 我会在答案中添加一些数组的内容。
    • 我编辑了答案以包含数组函数
    • 当我复制\粘贴此代码时 - 服务器回答 500 http 错误:(
    • 您使用的是什么 PHP 版本?我对其进行了调整,因此它也适用于 7 以下的 PHP 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    相关资源
    最近更新 更多