Skip to content

Instantly share code, notes, and snippets.

@borisguery
Created September 21, 2012 08:45
Show Gist options
  • Save borisguery/3760428 to your computer and use it in GitHub Desktop.
Save borisguery/3760428 to your computer and use it in GitHub Desktop.
Version to Integer
<?php
function version2integer($version) {
$matches = array();
preg_match('/([0-9.]+)/', $version, $matches);
if (count($matches) > 1) {
$maxSequences = 4; // v12.34.56.78.90 will stop at 78
$matches = explode('.', $matches[1]);
$matches = $matches + array(0, 0, 0, 0);
}
$normalizedVersion = '';
foreach ($matches as $match) {
if (0 === $maxSequences) break;
elseif (is_numeric($match)) {
$hex = sprintf('%002x', (int)$match);
$normalizedVersion .= $hex;
--$maxSequences;
}
}
return sprintf('%010d', hexdec($normalizedVersion));
}
// -----
$versions = array('1.1', '2.3','4.6.7', '4.3.0', '14.8', '123.9.0', '0.9', '4.7', '4.7.1', '4.6');
$integerVersions = array();
foreach ($versions as $version) {
$integerVersion = version2integer($version);
printf("%s => %s\n", $version, $integerVersion);
$integerVersions[(int)$integerVersion] = $version;
}
ksort($integerVersions);
print_r($integerVersions);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment