查找最新版本文件夹


Finding latest version Folder

让我们直接解决我的问题,这些是我的文件夹:

Smarty-3.1.13
Smarty-3.1.15
Smarty-3.1.16
Smarty-3.1.19

文件夹名就是这样得到的

$smarty_versions = glob("php/Smarty-*");

结果:

Array
(
    [0] => php/Smarty-3.1.13
    [1] => php/Smarty-3.1.15
    [2] => php/Smarty-3.1.16
    [3] => php/Smarty-3.1.19
)

现在我在找…他们……可以为glob设置一个regexp,以便只选择最新的文件夹。

实际上,我插入作为golb第一个参数的一切看起来像regexp失败了:)有一种方法可以这样得到最后一个文件夹吗?

还是让我像……

$smarty_versions = glob("php/Smarty-*");
$latest_smarty_version = $smarty_versions[count($smarty_versions)-1]; 
//works but i like it more tiny if possible :)

也许你们知道另一个单行解决方案:D

要使用正确的版本字符串比较,您应该使用version_compare:

$latest = array_reduce($smarty_versions, function ($latest, $folder) {
    if (!$latest) {
        return $folder;
    }
    $latestNum = preg_replace('!^php/Smarty-!', '', $latest);
    $folderNum = preg_replace('!^php/Smarty-!', '', $folder);
    return version_compare($latestNum, $folderNum, '>') ? $latest : $folder;
});

当然前提是Smarty版本遵循与函数期望的兼容约定