note 87322 deleted from function.version-compare by danbrown
| From: | danbrown@php.net | Date: | Sat, 24 Jan 2009 00:47:14 +0000 |
| Subject: | note 87322 deleted from function.version-compare by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-149723@lists.php.net to get a copy of this message | ||
Note Submitter: ben at simplescripts dot com
----
There may be a faster way to do some of this, but I needed to take into account gamma and service
pack releases. I had no need for the comparison operator functionality, so that does not exist in
this version.
<?php
function versionCompare($v1, $v2) {
//reformat v1
$v1 = str_replace(array('_','-','+'),'.',strtolower($v1));
$v1 = str_replace(array('alpha','beta','gamma'),
array('a','b','g'), $v1);
$v1 = preg_split("/([a-z]+)/i",$v1,-1, PREG_SPLIT_DELIM_CAPTURE);
array_walk($v1, create_function('&$v', '$v = trim($v,". ");'));
$v1 = explode('.',trim(implode('.',$v1),'. '));
//reformat v2
$v2 = str_replace(array('_','-','+'),'.',strtolower($v2));
$v2 = str_replace(array('alpha','beta','gamma'),
array('a','b','g'), $v2);
$v2 = preg_split("/([a-z]+)/i",$v2,-1, PREG_SPLIT_DELIM_CAPTURE);
array_walk($v2, create_function('&$v', '$v = trim($v,". ");'));
$v2 = explode('.',trim(implode('.',$v2),'. '));
//start comparison by padding sizes
if (count($v1) < count($v2)) { $v1 = array_pad($v1, count($v2), '0'); }
elseif (count($v1) > count($v2)) { $v2 = array_pad($v2, count($v1), '0'); }
//order chart
$chart =
array('dev','a','b','g','rc','pl','0','sp');
foreach ($v1 as $n => $v) {
//check if equal
if ($v === $v2[$n]) { continue; }
//check if both numbers
if (preg_match("/^[0-9]+$/",$v) && preg_match("/^[0-9]+$/",$v2[$n])) {
if ($v < $v2[$n]) { return -1; }
if ($v > $v2[$n]) { return 1; }
}
//check if one number (not 0)
if (preg_match("/^[0-9]+$/",$v) && $v != '0') { return 1; }
if (preg_match("/^[0-9]+$/",$v2[$n]) && $v2[$n] != '0') { return -1; }
//account for both being symbols (and/or zeros)
if (array_search($v, $chart) < array_search($v2[$n], $chart)) { return -1; }
if (array_search($v, $chart) > array_search($v2[$n], $chart)) { return 1; }
return false;
}
return 0; //return 0 if equal
}
//using old function returns -1, as SP is not recognized.
var_dump(version_compare("2.2.RC.2SP1","2.2.RC.2"));
//using new function returns 1, as you'd expect.
var_dump(versionCompare("2.2.RC.2SP1","2.2.RC.2"));
?>