Удалить URL хвост и оставить только домен - PullRequest
0 голосов
/ 02 ноября 2019

У меня есть скрипт, на который я отправляю список ссылок. Как удалить URL-адрес и оставить только домен? Например: вместо google.com/adwords оставьте только google.com.

<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));

, но это не работает.

1 Ответ

0 голосов
/ 02 ноября 2019
// 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 для получения дополнительной информации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...