简体   繁体   English

PHP:version_compare() 在比较 5.2 和 5.2.0 时返回 -1?

[英]PHP: version_compare() returns -1 when comparing 5.2 and 5.2.0?

version_compare('5.2', '5.2.0'); // returns -1, as if the second parameter is greater!

Isn't 5.2 and 5.2.0 suppose to be equal? 5.2 和 5.2.0 不是应该相等吗? (isn't 5.2 and 5.2.0.0 are also equal)? (是不是 5.2 和 5.2.0.0 也相等)?

The documentation says it compares 'two "PHP-standardized" version number strings'.文档说它比较了“两个“PHP 标准化”版本号字符串。

You're comparing one PHP-standardized version number string with one non-PHP-standardized version number string.您正在将一个 PHP 标准化版本号字符串与一个非 PHP 标准化版本号字符串进行比较。

Here's a tweaked compare function which behaves as expected by trimming zero version suffix components, ie 5.2.0 -> 5.2 .这是一个经过调整的比较函数,它通过修剪零版本后缀组件来按预期运行,即5.2.0 -> 5.2

var_dump(my_version_compare('5.1', '5.1.0'));           //  0 - equal
var_dump(my_version_compare('5.1', '5.1.0.0'));         //  0 - equal
var_dump(my_version_compare('5.1.0', '5.1.0.0-alpha')); //  1 - 5.1.0.0-alpha is lower
var_dump(my_version_compare('5.1.0-beta', '5.1.0.0'));  // -1 - 5.1.0-beta is lower

function my_version_compare($ver1, $ver2, $operator = null)
{
    $p = '#(\.0+)+($|-)#';
    $ver1 = preg_replace($p, '', $ver1);
    $ver2 = preg_replace($p, '', $ver2);
    return isset($operator) ? 
        version_compare($ver1, $ver2, $operator) : 
        version_compare($ver1, $ver2);
}

5.2 and 5.2.0 are both PHP-standardized version number strings. 5.2 和 5.2.0 都是 PHP 标准化的版本号字符串。 AFAIU 5.2 represents 5.2.0, 5.2.1, etc. And result is logical, 5.2 could not be equal to 5.2.1 or 5.2.0 and either it could not be greater than 5.2.0 for example. AFAIU 5.2 代表 5.2.0、5.2.1 等。结果是合乎逻辑的,例如 5.2 不能等于 5.2.1 或 5.2.0 并且不能大于 5.2.0。
So only expected behavior is 5.2 < 5.2.0, 5.2 < 5.2.1, ...所以只有预期的行为是 5.2 < 5.2.0, 5.2 < 5.2.1, ...

Btw even the documentation states:顺便说一句,甚至文档指出:

This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also ...这样不仅可以比较具有不同级别的版本,例如“4.1”和“4.1.2”,而且...

Quick PHP function to figure out whether a version is greater than other:快速判断某个版本是否大于其他版本的 PHP 函数:

$v1 = "1.101.9999";
$v2 = "1.2";

if ( semver($v1, $v2) ) {
    echo "v1 is greater than v2";
}

function semver($v1, $v2, $version_separator = ".") {

    // DTSC
    $v1_sub = explode($version_separator, $v1);
    $v2_sub = explode($version_separator, $v2);

    for ($i=0; $i < sizeof($v1_sub); $i++) {

        if ( !isset($v2_sub[$i]) ) {
            $v2_sub[$i] = 0;
        }
    
        if ( intval($v1_sub[$i]) > intval($v2_sub[$i]) ) {
            return true;
        } else if ( intval($v1_sub[$i]) < intval($v2_sub[$i]) ) {
            return false;
        }
    
    }

    return false; // Versions are equal - Change this value if you need a specific return for equal versions
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM