Skip to content

Instantly share code, notes, and snippets.

@stevenrombauts
Last active March 14, 2019 10:00
Show Gist options
  • Save stevenrombauts/7272122 to your computer and use it in GitHub Desktop.
Save stevenrombauts/7272122 to your computer and use it in GitHub Desktop.
Parse version numbers into major/minor/patch values
<?php
$versions = array('1.0 RC1', '1.0 RC2', '1.0 RC3', '1.0 RC4', '1.0 RC5', '1.0 RC6', '1.5.0', '1.5.1', '1.5.10', '1.5.11', '1.5.12', '1.5.13', '1.5.14', '1.5.15', '1.5.2', '1.5.3', '1.5.4', '1.5.5', '1.5.6', '1.5.7', '1.5.8', '1.5.9', '1.6.0', '1.6.1', '1.6.2', '1.6.3', '1.6.4', '1.6.5', '1.6.6', '1.6.7', '5.3.5-1ubuntu7.11', '2.14 RC1', '3.12RC5');
foreach($versions as $version)
{
$result = preg_match("/^(\d+)\.(\d+)[\. \-]?([a-z0-9\-\.]+)$/i", $version, $matches);
if($result)
{
$major = (int) $matches[1];
$minor = (int) $matches[2];
$patch = $matches[3];
if(is_numeric(substr($patch, 0, 1))) {
echo "Parsed $version to: $major.$minor.$patch";
} else {
echo "Parsed $version to: $major.$minor $patch";
}
}
else echo "!! No match found for $version !!";
echo PHP_EOL;
}
@manavo
Copy link

manavo commented Nov 26, 2016

Making the patch version optional makes this a bit more versatile. So after the patch version, make the + a ?. Just made it more useful for me. Thanks for this 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment