2011-12-28 85 views
1

我發現此解決方案規範化並匹配相同的URL,但我想知道是否有更優雅的東西,PHP不具有URL規範化功能?使用規範化/規範化匹配URL

function urlMatch($url1, $url2) 
{ 
    // parse the urls 
    $r1 = parse_url($url1); 
    $r2 = parse_url($url2); 

    // get the variables out of the queries 
    parse_str($r1['query'], $v1); 
    parse_str($r2['query'], $v2); 

    // match the domains and paths 
    if ($r1['host'] != $r2['host'] || $r1['path'] != $r2['path']) 
     return false; 

    // match the arrays 
    foreach ($v1 as $key => $value) 
     if (array_key_exists($key, $v2) && $value != $v2[$key]) 
      return false; 

    // if we haven't returned already, then the queries match 
    return true; 
} 
+0

重新標記添加規範化和消除規範化。在SO的上下文中,「標準化」標籤是指數據庫標準化。規範化更有可能吸引合適類型的專家。 – 2011-12-28 03:32:42

+0

此功能錯誤!那麼'schema'和'port'呢?或其他參數只存在於第二個網址? – 2011-12-28 03:37:27

+0

我想我現在需要更優雅更正確的東西:( – 2011-12-28 03:43:38

回答

1

像這樣的東西可能會滿足您的需求更適合:

function urlMatch($url1, $url2){ 
    // parse the urls 
    $r1 = parse_url($url1); 
    $r2 = parse_url($url2); 

    if (isset($r1['query'])){ 
    // get the variables out of the query 
    parse_str($r1['query'], $v1); 
    // sort arguments so they be in exactly same order 
    asort($v1); 
    // place sorted arguments back 
    $r1['query'] = http_build_query($v1); 
    } 

    if (isset($r2['query'])){ 
    parse_str($r2['query'], $v2); 
    asort($v2); 
    $r2['query'] = http_build_query($v2); 
    } 

    // Match re-constructed urls (you'll need pecl_http extension for this) 
    $matched = http_build_url($r1) === http_build_url($r2); 

    return $matched; 
} 

更新:我已經改變了代碼一點對付空查詢...