PHP url数组搜索并返回最接近的url

时间:2017-10-03 00:57:02

标签: php arrays string substring

我有以下数组与网址

$data = Array ( 'http://localhost/my_system/users',
        'http://localhost/my_system/users/add_user', 
        'http://localhost/my_system/users/groups',
        'http://localhost/my_system/users/add_group' );

然后我有一个变量

$url = 'http://localhost/my_system/users/by_letter/s';

如果$ url不存在,我需要一个能从数组返回最接近url的函数。像

这样的东西
function get_closest_url($url,$data){

}



get_closest_url($url,$data); //returns 'http://localhost/my_system/users/'

$url2 = 'http://localhost/my_system/users/groups/ungrouped';

get_closest_url($url2,$data); //returns 'http://localhost/my_system/users/groups/'

$url3 = 'http://localhost/my_system/users/groups/add_group/x/y/z';

get_closest_url($url3,$data); //returns 'http://localhost/my_system/users/groups/add_group/'

2 个答案:

答案 0 :(得分:1)

您可以在$data中分解当前URL和每个URL,与数组相交,然后返回具有最多元素的数组(最佳匹配)。如果没有匹配项,请返回false

<?php
$data = [ "localhost/my_system/users",
        "localhost/my_system/users/add_user", 
        "localhost/my_system/users/by_letter/groups",
        "localhost/my_system/users/add_group"];
$url = "localhost/my_system/users/by_letter/s";
function getClosestURL($url, $data) {
    $matches = [];
    $explodedURL = explode("/", $url);
    foreach ($data as $match) {
        $explodedMatch = explode("/", $match);
        $matches[] = array_intersect($explodedMatch, $explodedURL);
    }
    $bestMatch = max($matches);
    return count($bestMatch) > 0 ? implode("/", $bestMatch) : false; // only return the path if there are matches, otherwise false
}

var_dump(getClosestURL($url, $data)); //returns localhost/my_system/users/by_letter
var_dump(getClosestURL("local/no/match", $data)); //returns false

Demo

您没有提及如何专门检查网址是否存在。如果需要“实时”,您可以使用get_headers()并检查HTTP状态的第一项。如果它不是200,那么您可以继续使用URL交集。

$headers = get_headers($url);
$httpStatus = substr($headers[0], 9, 3);
if ($httpStatus === "200") {
    return $url; // $url is OK
}
// else, keep going with the previous function

答案 1 :(得分:0)

function get_closest_url($item,$possibilities){
    $result = [];
    foreach($possibilities as $possibility){
        $lev = levenshtein($possibility, $item);
        if($lev === 0){
            #### we have got an exact match
            return $possibility;
        }
        #### if two possibilities have the same lev we return only one
        $result[$lev] = $possibility;
    }
    #### return the highest
    return $result[min(array_keys($result))];
}

应该这样做。