php获取版本号的相邻版本

镜面王子
  • 69

假设我当前版本号定义是 1.0.9;下个版本号会是1.1.0;逢十进一.

<?php
$version='1.0.9';

请问如何计算出前一个版本是1.0.8;
后一个版本是1.1.0;

回复
阅读 2.7k
2 个回答
上官元恒
  • 8.7k
✓ 已被采纳
<?php
/**
 * 版本自增/自减
 *
 * @author zhusaidong <zhusaidong@gmail.com>
 */
$currentVersion = '0.1.9';
var_dump(versionUp($currentVersion));//string(5) "0.2.0"
var_dump(versionDown($currentVersion));//string(5) "0.1.8"

function versionUp(string $currentVersion) : string
{
    $currentVersion = str_replace('.', '', $currentVersion);
    
    $version = (int)$currentVersion;
    $version++;
    $version = str_pad($version, strlen($currentVersion), '0', STR_PAD_LEFT);
    $version = substr_replace($version, '.', strlen($version) - 1, 0);  
    $version = substr_replace($version, '.', strlen($version) - 3, 0);
    
    return $version;
}

function versionDown(string $currentVersion) : string
{
    $currentVersion = str_replace('.', '', $currentVersion);
    
    $version = (int)$currentVersion;
    if($version > 1)
    {
        $version--;
    }
    $version = str_pad($version, strlen($currentVersion), '0', STR_PAD_LEFT);
    $version = substr_replace($version, '.', strlen($version) - 1, 0);  
    $version = substr_replace($version, '.', strlen($version) - 3, 0);
    
    return $version;
}
Tuesday
  • 138

不是有规律吗?

你直接切割成数组处理即可.

$ver = '12.9.9';

$ver = strtr($ver, array('.'=>''));
$newver = $ver+1;  // add 1

echo $newver = substr_replace($newver, '.', strlen($ver)-1,0);
echo '<br />';
echo substr_replace($newver, '.', strlen($ver)-2,0);
exit;
宣传栏