Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare version #'s inside a string?

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.

like image 233
user797963 Avatar asked May 15 '26 20:05

user797963


2 Answers

Shouldn't you be using? version_compare(ver1, ver2)

http://php.net/manual/en/function.version-compare.php

like image 168
MisRoy Avatar answered May 17 '26 10:05

MisRoy


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.

like image 43
Sean Avatar answered May 17 '26 08:05

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!