Reputation: 3037
I need to compare two version #'s to see if one is greater than the other and am having a really hard time doing so.
version 1: test_V10.1.0.a.1@example version 2: test_V9.7.0_LS@example
I've tried stripping all non numeric characters out so I would be left with:
version1: 10101 version2: 970
Which drops the 'a' from 10.1.0.a.1 so that's no good, and I've tried taking everything between 'test_' and '@' then stripping out anything to the right of an underscore '_' and the underscore itself, but then I still have to strip out the 'V' at the beginning of the string.
Even if I can get down to just 10.1.0.a.1 and 9.7.0, how can I compare these two? How can I know if 10.1.0.a.1 is greater than 9.7.0? If I strip the decimals out I'm still left with a non numeric character in 1010a1, but I need that character in case say the release version I'm comparing this to is 10.1.0.b.1, this would be greater than 10.1.0.a.1.
This is driving me nuts, has anyone dealt with this before? How did you compare the values? I'm using php.
Upvotes: 3
Views: 1364
Reputation: 131
Shouldn't you be using? version_compare(ver1, ver2)
http://php.net/manual/en/function.version-compare.php
Upvotes: 5
Reputation: 5768
Use explode('.', $versionNum)
$ver1 = '10.1.0.a.1';
$ver2 = '10.1.0';
$arr1 = explode('.', $ver1);
$arr2 = explode('.', $ver2);
$min = min(count($arr1), count($arr2));
for ($i = 0; $i < $min; $i++)
{
if ($i + 1 == $min)
echo ($min == count($arr1)) ? $ver2 : $ver1;
if ($arr1[$i] > $arr2[$i])
{
echo $ver1;
break;
}
elseif ($arr1[$i] < $arr2[$i])
{
echo $ver2;
break;
}
}
Upvotes: 3
Reputation: 12332
The following regular expression will match everything between "test_V" and "@example" and throw it into an array called $matches[1]
$pattern = '/test_V(.*?)(?:_.*?)?@example/i';
$string = 'version 1: test_V10.1.0.a.1@example version 2: test_V9.7.0_LS@example';
if(preg_match_all($pattern,$string,$matches))
{
print_r($matches[1]);
}
returns
Array
(
[0] => 10.1.0.a.1
[1] => 9.7.0
)
This will give you a head start in figuring out how you want to pull apart your fairly complex version number.
Upvotes: 1
Reputation: 564
I think you want to consider working with a regex to parse out the "number" part of the version numbers - "10.1.0.a.1" and "9.7.0". After that, you can split by '.' to get two "version arrays".
With the version arrays, you pop elements off them until you find a higher number. Whichever array it came from is the higher version number. If either array runs out, it's a lesser version number (unless all the remaining elements are "0" or "a" or whatever semantics you use to say "base version", e.g., "10.0.0.a.0" == "10.0"). If both run out at the same time, then they're equal.
Upvotes: 4