[英]Matching URLs with normalisation/canonicalisation
我发现此解决方案可以标准化和匹配相等的URL,但是我想知道是否还有其他更优雅的方法,PHP是否没有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;
}
这样的事情可能更适合您的需求:
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;
}
更新:我对代码进行了一些更改以处理空查询...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.