How to compare version # inside a string?

I need to compare the two # versions to see if one of them is bigger than the other, and it’s really hard for me to do this.

version 1: test_V10.1.0.a.1@example version 2: test_V9.7.0_LS@example

I tried to remove all non-digital characters, so I would stay with:

version1: 10101 version2: 970

Which is β€œa” from 10.1.0.a.1, so that’s nothing good, and I tried to take everything between β€œtest_” and β€œ@”, and then delete everything that’s to the right of the underscore β€œ_”, and the underscore itself but then I still need to cut "V" at the beginning of the line.

Even if I can only go to 10.1.0.a.1 and 9.7.0, how can I compare these two? How can I find out if 10.1.0.a.1 is greater than 9.7.0? If I delete the decimals, I still remain with the numeric character in 1010a1, but I need this character in case the release version I am comparing is 10.1.0.b.1, it will be more than 10.1.0 .a.1.

It drives me crazy, has anyone talked about this before? How did you compare the values? I am using php.

+3
source share
4 answers

I think you want to consider working with a regular expression to parse the "number" of the version number part - "10.1.0.a.1" and "9.7.0". After that you can split on '.' to get two "version arrays".

, . , . - , ( "0" "" - , , " ", "10.0.0.a.0" == "10,0" ). , .

+4
+5

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;
    }
}
+3

"test_V" "@example" $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]);
}

Array
(
    [0] => 10.1.0.a.1
    [1] => 9.7.0
)

, .

+1

All Articles