比较来自URL数组的主机名并获得唯一的值



我需要比较URL并从数组中删除重复项,但我希望仅从URL中比较主机。当我比较时,我需要跳过HTTP和HTTP和www,以及其他其他人。所以当我有数组时:

    $urls = array(
'http://www.google.com/test', 
'https://www.google.com/test',
'https://www.google.com/example', 
'https://www.facebook.com/example',
'http://www.facebook.com/example');

结果只有

http://www.google.com/test
http://www.google.com/example
http://www.facebook.com/example

我试图比较:

$urls = array_udiff($urls, $urls, function ($a, $b) {
                 return strcmp(preg_replace('|^https?://(www\.)?|', '', rtrim($a,'/')), preg_replace('|^https?://(www\.)?|', '', rtrim($b,'/')));
            });

但是它将我返回空数组。

<?php
   $urls = array(
    'http://www.google.com/test',
    'https://www.google.com/test',
    'https://www.google.com/example',
    'https://www.facebook.com/example',
    'http://www.facebook.com/example');

$MyArray = [];
for($i=0;$i<count($urls);$i++)  {
preg_match_all('/www.(.*)/', $urls[$i], $matches);
    if (!in_array($matches[1], $MyArray))
        $MyArray[] = $matches[1];
}
echo "<pre>";
print_r($MyArray);
echo "</pre>";

,输出为

Array
(
    [0] => Array
        (
            [0] => google.com/test
        )
    [1] => Array
        (
            [0] => google.com/example
        )
    [2] => Array
        (
            [0] => facebook.com/example
        )
)

修剪并仅保留主机名

尝试以下方法:

<?php
function parseURLs(array $urls){
    $rs = [];
    foreach($urls as $url){
        $segments = parse_url($url);
        if(!in_array($segments['host'], $rs))
            $rs[] = $segments['host'];
    }
    return $rs;
}

然后:

<?php
$urls = array(
    'http://www.google.com',
    'https://www.google.com',
    'https://www.google.com/',
    'https://www.facebook.com',
    'http://www.facebook.com'
);
$uniqueURLs = parseURLs($urls);
print_r($uniqueURLs);
/* result :
Array
(
    [0] => www.google.com
    [1] => www.facebook.com
)
*/

您需要循环遍历URL,用PHP的url_parse()函数解析URL,并使用Array_unique从数组中删除重复项,因此我们同时检查了主机和路径。

我为您写了一堂课:

<?php
/** Get Unique Values from array Values **/
Class Parser {
    //Url Parser Function
    public function arrayValuesUrlParser($urls) {
        //Create Container
        $parsed = [];
        //Loop Through the Urls
        foreach($urls as $url) {
            $parse = parse_url($url);
            $parsed[] = $parse["host"].$parse["path"];
            //Delete Duplicates
            $result = array_unique($parsed);
        }
        //Dump result
        print_r($result);
    }
}
?>

使用类

<?php
//Inlcude tghe Parser
include_once "Parser.php";
    $urls = array(
    'http://www.google.com/test', 
    'https://www.google.com/test',
    'https://www.google.com/example', 
    'https://www.facebook.com/example',
    'http://www.facebook.com/example');
    //Instantiate
    $parse = new Parser();
    $parse->arrayValuesUrlParser($urls);
?>

,如果您不需要单独的文件,则可以在一个文件中执行此操作,但是如果您使用一个PHP文件,则必须删除Include_once。此课程也在PHP课程上,为了娱乐而做!

好运!

最新更新