PHP Classes

This was nominated why?

Recommend this page to a friend!

      PHP URL Compare  >  All threads  >  This was nominated why?  >  (Un) Subscribe thread alerts  
Subject:This was nominated why?
Summary:URL comparison done in 1/5th the code
Messages:1
Author:Michael Richey
Date:2013-11-01 18:59:17
 

  1. This was nominated why?   Reply   Report abuse  
Picture of Michael Richey Michael Richey - 2013-11-01 18:59:17
Even more useful than just printing the differences (what's up with that?). This returns an array of differences - or a true/false if a specific URL component is to be tested - in 42 lines:

class URLCompare {
private $url;
public function __construct($url) {
$this->url = parse_url($url);
if(isset($this->url['query'])) $this->url['query']=$this->parseQuery($this->url['query']);
}
public function compareURL($url,$component=false) {
$url = parse_url($url);
if(isset($url['query']))
$url['query']=$this->parseQuery($url['query']);
if($component) {
return $this->url[$component]==$url[$component];
} else {
return $this->arrayRecursiveDiff($this->url, $url);
}
}
private function parseQuery($query) {
$retarray = array();
$query = explode('&',$query);
foreach($query as $qv) {
$qv = explode('=',$qv);
$retarray = (count($qv) == 2)?$qv[1]:$qv[0];
}
return $retarray;
}
private function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) $aReturn[$mKey] = $aRecursiveDiff;
} else {
if ($mValue != $aArray2[$mKey]) $aReturn[$mKey] = $mValue;
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
}

$url = new URLCompare('http://www.google.com/index.php?this=that&a=b');
print_r($url->compareURL('http://www.yahoo.com/index.php?this=that'));
Array
(
[host] => www.google.com
[query] => Array
(
[a] => b
)

)